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

青春须早为,岂能长少年。这篇文章主要讲述Django民意调查app没有选择和点击选票投票相关的知识,希望能为你提供帮助。
问题陈述:我是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 = "https://www.songbingjia.com/android/{{j.id}}"/> < label for ="j{{forloop.counter}}"> {{j.choice_text}}< /label> < br> {% endfor %} < input type = "submit" value = "https://www.songbingjia.com/android/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 ="https://www.songbingjia.com/android/{% 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
谢谢,请让我知道任何进一步的信息。
答案将您的代码更改为:
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参数是否在POST中,如果不是我们返回错误,你的try, except, else将无法工作因为你正在使用nude except所以else条件永远不会被执行。
【Django民意调查app没有选择和点击选票投票】如果它对你有所帮助,请告诉我

    推荐阅读