Django民意调查app没有选择和点击选票投票

时间:2018-03-03 00:11:00

标签: python django django-views

问题陈述: 我是Django的新手,并尝试民意调查应用程序。我目前在我们创建投票功能的地方接受投票并显示结果。但面临的问题是它没有获得投票权。当我进入结果页面时,它会显示名称但没有投票。下面是代码和剪辑。

 def results(request, question_id):
    i = get_object_or_404(Question, pk=question_id)
    return render(request, "span/results.html", {'i': i})


def vote(request, question_id):
    i = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = i.choice_set.get(pk=request.POST['choice'])
    except:
        return render(request, 'span/detail.html', {'i': i, 'error_message': "Please select a choice "})
    else:
        selected_choice.votes += 1
        selected_choice.save()

        return HttpResponseRedirect(reverse('span:results', args=(i.id,)))

以上是我的views.py

及以下显示我的细节:

{% extends 'span/base.html' %}

{%block main_content %}
<h1> {{i.question_text}}</h1>
{% if error_message %} <p><strong>{{error_message}}</strong></p>{% endif %}
<form action = "{%  url 'span:vote' i.id %}" method = "post">
    {% csrf_token %}
    {% for j in i.choice_set.all %}
        <input type = "radio" name = "j" id="j{{forloop.counter}}" value = "{{j.id}}"/>
        <label for ="j{{forloop.counter}}">{{j.choice_text}}</label> <br>
    {% endfor %}
    <input type = "submit" value = "vote">
</form>


{% endblock %}

和我的结果

{% extends 'span/base.html' %}

{% block main_content %}

<h1> {{i.question_text}}</h1>

<ul>
    {% for j in i.choice_set.all %}
        <li>
            {{j.choice_text}} -- {{j.votes}} vote{{ j.votes|pluralize}}

        </li>
    {% endfor %}
</ul>

<a href =  "{% url 'span:detail' i.id %}"> vote again? </a>
{% endblock %}

还添加剪辑:


Going to the 1st page

On selecting an Option and clicking on vote it directs me to the same page with an error message so basically, it's not recognising the input that's what I think

This is the result page it's not capturing the votes but ist displaying other thing and also the vote again option is working too

谢谢,请让我知道任何进一步的信息。

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

def vote(request, question_id):
    i = get_object_or_404(Question, pk=question_id)
    if request.method == 'POST':
        if request.POST["choice"]:
            selected_choice = i.choice_set.get(pk=request.POST['choice'])
            selected_choice.votes += 1
            selected_choice.save()
            return HttpResponseRedirect(reverse('span:results', args=(i.id,)))
        else:
            return render(request, 'span/detail.html', {'i': i, 'error_message': "Please select a choice "})
    return render(request, 'span/detail.html', {'i': i})

解释

首先你必须知道正在使用什么方法,在这种情况下我们需要POST这就是我添加条件的原因,然后我们检查choice参数是否来自{{1如果不是,我们会返回错误,POST因为您使用的是try, except, else而无法正常工作,因此其他条件永远不会被执行。

让我知道它是否对你有帮助