django教程 - 在网站上添加民意调查

时间:2014-04-05 12:56:02

标签: python django python-2.7

我刚刚完成了django教程1-6。

我想这样做,以便可以在index.html中添加一个民意调查。我发现必须在管理员中执行它是非常不方便的,我不明白为什么他们没有将它添加到教程中。了解这将是一个很棒的功能。

我已设法从标签中获取文本字段,当按下输入时,该网站变为空白,我必须重新加载才能返回投票。当然还没有新的民意调查。

这是我到目前为止所尝试的内容:

的index.html:

<form action='' method='post'> {% csrf_token %}
    {{ form.add_poll }}
    <input class='btn btn-default' type='text'>
</form>

views.py - indexview,我在其中添加了一些

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        """
        Return the last five published polls (not including those set to be
        published in the future).
        """
        return Poll.objects.filter(
            pub_date__lte=timezone.now()
        ).order_by('-pub_date')[:5]

        add_poll = ComposePoll(request.POST or None)
        if add_poll.is_valid():
            create_poll = Poll.save(commit=False)
            create_poll.sent = datetime.datetime.now()
            create_poll.save()
            return HttpResponseRedirect('/polls/')

        poll = Poll.objects.filter()

        return render_to_response('polls/index.html', locals(), context_instance=RequestContext(request))

forms.py - 我添加了forms.py。它不在教程中。我重复使用了admin.py中的一些

class ComposePoll(forms.ModelForm):
    class Meta:
        fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), 
        ]

1 个答案:

答案 0 :(得分:0)

你不能在get_queryset()中这样做。从那里返回唯一的东西是一个查询集,顾名思义,而不是重定向。您应该覆盖get()