在外键中获取父元素的上下文 - Django

时间:2011-05-09 08:06:12

标签: django django-views

这应该是非常简单的,它在文档中。我试图获取ListView的上下文。例如:

“我们也可以同时将发布商添加到上下文中,因此我们可以在模板http://docs.djangoproject.com/en/1.3/topics/class-based-views/#dynamic-filtering/中使用它:

class IssuesByTitleView(ListView):
    context_object_name = "issue_list"
    def get_queryset(self):
        self.title = get_object_or_404(Title, slug=self.kwargs['title_slug'])
        return Issue.objects.filter(title=self.title).order_by('-number')

我的models.py看起来像这样:

class Title(models.Model):
    CATEGORY_CHOICES = (
    ('Ongoing', 'Ongoing'),    
    ('Ongoing - Canceled', 'Ongoing - Canceled'),
    ('Limited Series', 'Limited Series'),
    ('One-shot', 'One-shot'),
    ('Other', 'Other'),
    )    
    title = models.CharField(max_length=64)
    vol = models.IntegerField(blank=True, null=True, max_length=3)
    year = models.CharField(blank=True, null=True, max_length=20, help_text="Ex) 1980 - present, 1980 - 1989.")
    category = models.CharField(max_length=30, choices=CATEGORY_CHOICES)    
    is_current = models.BooleanField(help_text="Check if the title is being published where Emma makes regular appearances.")
    slug = models.SlugField()
    class Meta:
        ordering = ['title']
    def get_absolute_url(self):
        return "/titles/%s" % self.slug        
    def __unicode__(self):
        return self.title

    class Issue(models.Model):
        CATEGORY_CHOICES = (
        ('Major', 'Major'),    
        ('Minor', 'Minor'),
        ('Cameo', 'Cameo'),
        ('Other', 'Other'),
        )
        title = models.ForeignKey(Title)
        number = models.IntegerField(help_text="Do not include the '#'.")

        .........

Views.py:

class IssuesByTitleView(ListView):
    context_object_name = "issue_list"
    def get_queryset(self):
        self.title = get_object_or_404(Title, slug=self.kwargs['title_slug'])
        return Issue.objects.filter(title=self.title).order_by('-number')
    def get_context_data(self):
        context = super(IssuesByTitleView, self).get_context_data()
        context['title'] = self.title
        return context

在标题中的问题列表中,我需要返回标题和标题的所有其他属性。那不起作用,它返回一个错误:

  

get_context_data()得到了一个意外的关键字参数'object_list'

1 个答案:

答案 0 :(得分:2)

你应该在get_context_data

中使用** kwargs
def get_context_data(self, **kwargs):
    context = super(IssuesByTitleView, self).get_context_data(**kwargs)
    context['title'] = self.title
    return context