使用django消息框架来显示用户是否已经投票

时间:2014-06-04 16:14:57

标签: python django

如果用户已经投票,我需要检查并显示django消息框架,然后显示在结果页面中,您已经投票,但如果他没有则显示您的投票已保存。所以我添加了成功消息,但是我不知道如何检查用户是否已投票。

my models.py

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __uncidoe__(self):
        return self.question

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.choice_text

my views.py

def results(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id) 
    messages.add_message(request, messages.SUCCESS, 'Your vote has been saved !!!')
    return render(request, 'polls/results.html', {'poll': poll})

我的results.html

{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{message.tags}}" {% endif %}>{{message}}</li>
{% endfor %}
</ul>
{%endif%}

修改

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

我的投票def

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render(request, 'polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

1 个答案:

答案 0 :(得分:0)

添加新模型以存储每个用户的投票。虚拟解决方案:

class UserVote(models.Model):
    pool = models.ForeignKey(Pool)
    user = models.ForeignKey(User)
    choice = models.ForeignKey(Choice)

    class Meta:
        unique_together = ('pool', 'user')

并查看处理用户的选择提交:

def send_result(request, poll_id, choice_id):

    poll = get_object_or_404(Poll, pk=poll_id)

    vote, created = UserVote.objects.get_or_create(pool=pool, user=request.user, defaults={'choice': choice_id})
    if created:
        messages.add_message(request, messages.SUCCESS, 'Your vote has been saved !!!')
    else:
        messages.add_message(request, messages.ERROR, 'Your already voted before !!!')
    return redirect(reverse('results', pool=pool_id))

显示投票表格的视图:

def vote_form(request, pool_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    choices = Choice.objects.filter(pool=pool)
    return render(request, 'vote_form.html', {'choices': choices, 'pool': pool})

及其模板:

<form action="{% url 'send_result' pool_id=pool.id %}">
    {% for choice in choices %}
        <input type="radio" name="choice_id" value="{{ choice.id }}"> {{ choice.choice_text }}<br />
        <input type="submit" value="vote">
    {% endfor %}
</form>