标签:
detail.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>
{% csrf_token %} 提交表单首先要做的,用于防止跨域攻击
{{ forloop.counter }} for标签自带的变量,统计for循环的次数
method="post",涉及数据库改变的药用post方法
urls.py
url(r‘^(?P<question_id>[0-9]+)/vote/$‘, views.vote, name=‘vote‘),
views.py
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,)))
request.POST是一个字典,键为input中的name,值为value
HttpResponseRedirect 处理完POST请求后要返回这个,而不是普通的HTTPResponse。能够避免数据被提交两次(用户按返回键时)
reverse 避免硬编码,会自动生成一个URL字符串
标签:
原文地址:http://www.cnblogs.com/roronoa-sqd/p/4916152.html