码迷,mamicode.com
首页 > 其他好文 > 详细

Django表单

时间:2018-04-03 14:25:42      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:owa   osx   ace   mwl   pmf   btv   arp   bst   vdp   

修改polls/templates/polls/detail.html,

以便模板包含一个HTML <form>元素:

技术分享图片

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

 

修改polls/views.py:

技术分享图片

 

技术分享图片

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

from .models import Question, Choice


def index(request):
latest_question_list = Question.objects.order_by(‘-pub_date‘)[:5]
context = {‘latest_question_list‘: latest_question_list}
return render(request, ‘polls/index.html‘, context)


def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, ‘polls/detail.html‘, {‘question‘: question})


def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, ‘polls/results.html‘, {‘question‘: 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):
return render(request, ‘polls/detail.html‘, {
# 重新显示问题投票的形式
‘question‘: question,
‘error_message‘: "You didn‘t select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse(‘polls:results‘, args=(question.id,)))
# 总是返回一个HttpResponseRedirect在数据成功处理后
# 这样可以防止数据在用户单击后退按钮时被重复两次

 

新建polls/results.html:

技术分享图片

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

 

启动服务

python manage.py runserver

访问
http://127.0.0.1:8000/polls/1/

技术分享图片

 

Django表单

标签:owa   osx   ace   mwl   pmf   btv   arp   bst   vdp   

原文地址:https://www.cnblogs.com/yjlch1016/p/8707773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!