扩展民意调查申请的问题

时间:2013-12-12 11:20:08

标签: django django-models django-views

我在民意调查应用程序中添加了一个额外的模型(请参阅django教程),该应用程序旨在成为一组问题的父级:

models.py
class Section(models.Model):
    section_text = models.CharField(max_length=255)
    section_description = models.TextField(blank=False)
    slug = models.SlugField(unique=True, null=True)

    def __unicode__(self):
        return self.section_text

    def save(self, *args, **kwargs):
        self.slug = slugify(self.section_text)
        super(Section, self).save(*args, **kwargs)


class Question(models.Model):
    section = models.ForeignKey(Section)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question_text

这在管理员中运行良好。每个问题都与一个部分相关联。

显示这些部分也没问题:

views.py
class UmfrageView(ListView):
    model = Section
    context_object_name = 'latest_section_list'
    template_name = 'umfrage.html'

但是如果我想通过slug传递一个部分到DetailView它不起作用(如果我使用generic.ListView,它会显示所有部分的问题):

urls.py
url(
    regex=r'^(?P<slug>[-\w]+)/$',
    view=DetailView.as_view(),
    name='detail'
),

views.py
class DetailView(ListView):
    model = Question
    context_object_name = 'latest_question_list'
    template_name = 'detail.html'

detail.html
{% if latest_question_list%}
    {% for question in latest_question_list %}
    <p>{{ question.question_text }}</p>
        {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
        <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
        {% endfor %}
    {% endfor %}
{% endif %}

如果我使用generic.DetailView

class DetailView(DetailView):
    [...]

出现以下错误:

“无法将关键字u'slug'解析为字段。选项包括:choice,id,pub_date,question_text,section”

我如何从一个特定部分获得一组问题,并且仍然通过slug获得人性化的URL?

谢谢!

(如果需要进一步的代码,我非常乐意更新)

1 个答案:

答案 0 :(得分:1)

DetailView添加方法get_queryset()中,仅返回所需的对象,如下所示

class DetailView(ListView):
    model = Question
    context_object_name = 'latest_question_list'
    template_name = 'detail.html'

    def get_queryset(self, **kwargs):
        slug = self.kwargs.get('slug') or kwargs.get('slug')
        if slug:
           return Question.objects.filter(section__slug=slug)
        else:
           return Question.objects.all()