1. Write a minimal form
Update the poll detail template (polls/detail.html
) and add a <form>
element to it.
polls/detail.html
<h1>{{ question.questionText }}</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.choiceText }}</label>
<br>
{% endfor %}
<input type="submit" value="Vote">
</form>
-
POST:
Whenever you create a form that change data server-side, usemethod="post"
. This tip isnt specific to Django; it's good Web development practice in general. -
csrf_token
:
All POST forms that are targeted at internal URLs should use the{% csrf_token %}
template tag. This can protect the site against Cross Site Request Forgeries.
网友评论