【问题标题】:Problems with extending the polls application扩展民意调查应用程序的问题
【发布时间】:2013-12-12 11:20:07
【问题描述】:

我在 polls 应用程序中添加了一个额外的模型(请参阅 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?

谢谢!

(如果需要更多代码,我很乐意更新)

【问题讨论】:

  • 欢迎来到 StackOverflow。请不要使用您的问题的标题来标记它;使用标记系统。

标签: django django-models django-views


【解决方案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()

【讨论】:

  • 你可以直接return Question.objects.filter(section__slug=slug) or Question.objects.all()
  • 这很完美:return Question.objects.filter(section__slug=slug).order_by('pub_date')
猜你喜欢
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 2015-12-01
相关资源
最近更新 更多