该代码段到底如何工作? “ pk = request.POST ['choice']”

时间:2018-06-28 03:33:28

标签: python django django-views

这来自Django文档中民意调查应用程序教程的第4部分。有人告诉我它以字符串的形式获取所选选项的ID。我想确切地知道它是怎么做到的。这里是一些上下文:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question
# ...
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

3 个答案:

答案 0 :(得分:2)

在此代码段中,您应该了解question_id来自您定义的路径。有关更多信息,请查看django url dispatcher documentation

例如,您应该将选择的ID发布到如下所示的网址(请注意,确切的用词取决于您定义的网址路径):

localhost:8000/questions/1/

对于此URL,如果您发布选择的ID,并且有一个发布ID的选择,则request.POST['choice']将获取发布的ID。的 然后,代码片段将以1作为ID的问题来增加对该选项的投票。

request.POST是一个字典,它引用http请求的已提交数据。与其他任何字典一样,您可以将键传递给request.POST以获取值。

答案 1 :(得分:0)

上一页的HTML:

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

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% 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 %}
<input type="submit" value="Vote" />
</form>

答案 2 :(得分:0)

{% 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>

此循环将创建具有相同名称“ choice”的单选按钮。多个共享相同名称的无线电称为RADIO GROUP。

在提交上述表单时,如果选择了单选按钮,则表单的数据将在choice = value表单中包含一个条目。 (在我们的案例中,每个单选按钮的值都不同)

因此,此摘录pk=request.POST['choice']从无线电组访问选定无线电的值(value="{{ choice.id }})。

我有同样的问题,下面的链接帮助我回答了这个问题。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio