本文介绍了基于类的视图Django多个子弹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 cbt个通用列表视图我要过滤两个子弹。但是 slug_url_kwargs 只允许传递单个字符串。如何更新 slug_url_kwarg 以支持多个子弹?或者我还能做什么?

I have cbt generic listview I want filtering with two slugs. But slug_url_kwargs only allows to pass single string. How can i update slug_url_kwarg to support multiple slugs? Or what can i do else?

所以我有这个模型并具有查看功能

So i have this models and view function

class SaityProfile(models.Model):
    user = models.ForeignKey(User, default=0)
    about = models.CharField(max_length=255, blank=True)
    name = models.CharField(max_length=255)
    url = models.CharField(max_length=255, unique=True)

    def __unicode__(self):
        return self.name







class Saity(models.Model):
    profile = models.ForeignKey('SaityProfile', null=True)
    user = models.ForeignKey(User, null=True)
    name = models.CharField(max_length=250)
    url = models.CharField(max_length=250, default=gen_slug_page)
    desc = models.CharField(max_length=250, blank=True)
    order = models.IntegerField(default=1)

    def get_absolute_url(self):
        return reverse('sites:website_pages', kwargs={'website_slug': self.url})







class WebsitesProfileList(generic.ListView):
    model = Saity
    slug_field = 'url'
    slug_field_kwargs = 'profile_url'
    template_name = 'saity_ds/websites_profile_list.html'

    def get_context_data(self, **kwargs):
        self.profile = SaityProfile.objects.get(url=self.kwargs['profile_url'])
        extra_context = {
            'profile': self.profile
        }
        context =  super(WebsitesProfileList, self).get_context_data(**kwargs)
        context.update(extra_context)
        return context

我的代码看起来像这样。我要添加新功能。我选择了基于类的视图,并且我认为这是我的错误,因为尚不清楚

My code looks similar like that. I want add new features. I have chosen class based view, and i think it is my mistake, because it is unclear

推荐答案

您不需要完全设置 slug_url_kwarg 。只需覆盖 get_queryset 并返回要显示视图的查询集即可。

You don't need to set slug_url_kwarg at all. Just override get_queryset and return the queryset that you want your view to display.

class WebsitesProfileList(generic.ListView):
    def get_queryset(self):
        return Saity.objects.filter(url=self.kwargs['url'], profile=self.kwargs['profile'])  # You will probably have to change this
    ...

这篇关于基于类的视图Django多个子弹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 20:51