Django part 4 --- Form

Form
这边介绍的from指的是HTML中的Form,前端HTML能给后台传数据有这么三种方式
  • url
  • form
  • hyperlink

polls.templates.polls.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">                       //数据传到 polls.vote方法
{% csrf_token %}                               //防跨域攻击
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"/>  //选项按扭,forloop.counter跟综循环的个数
    <labe for="choice{{ forloop.counter }}">{{ choice.choice_text }}</labe></br>
{% endfor %}
    <input type="submit" value="Vote"/>           //提交按钮
</form>
Django part 4 --- Form_第1张图片

polls.views.py
def vote(request,question_id):
    p = get_object_or_404(Question,pk=question_id)                      //get question
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])   //取前端选的choice
    except (KeyError,Choice.DoesNotExist):
        #Redisplay the question voting form.
        return render_to_response('polls/detail.html',{'question':p, 'error_message':"you don't select any choice"})
    else:
        selected_choice.votes += 1                   // 如果这个选项选中了,则它的属性值+1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results',args=(p.id,)))  //选中这个选项提交后,可以看result,传p.id是针对哪个问题的选项
        #return HttpResponseRedirect('/polls/%s/results' %question_id)
选择选项后,返回结果页面

polls.views.py
def results(request, question_id):
    questoin = get_object_or_404(Question,pk=question_id)
    return render_to_response('polls/results.html',{'question': questoin})
polls.templates.polls.results.html
<body>
<h1>{{ question.question_text }}</h1>

<ul>
    {% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote {{ choice.votes | pluralize }}</li>
    {% endfor %}
</ul>

<a href = "{% url 'polls:detail' question.id %}"> Vote again?</a>
</body> 
Django part 4 --- Form_第2张图片

显示这个问题不同选项的个数和结果,可见url模板非常好使,调用方法都可以使用,href, form action=等等

你可能感兴趣的:(django,form,url)