继上篇 django2.0入门教程第三节,介绍了django2.0的视图views和模板template, 本节介绍如何在前台进行投票。
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">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input id="choice{{ forloop.counter }}" type="radio" name="choice" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<br />
<input type="submit" name="" id="" value="投票" />
</form>
代码解析:
{%url 'polls:vote' question.id %}
, 即表示访问polls/views.py
的vote方法,并携带问题id作为参数。polls/urls.py
path('<int:question_id>/vote/', views.vote, name='vote'),
投票页面截图 http://127.0.0.1:8000/polls/1/ :
vote.png
polls/views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
# ...
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': "必须选择一个选项",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
代码解析:
request.POST['choice']
接收表单页面提交的数据polls/views.py
from django.shortcuts import render, get_object_or_404
# ...
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
results.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{choice.votes}}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">再投一次?</a>
提交结果页面 http://127.0.0.1:8000/polls/1/results/
result.png
另一种写法:
将主键id代替question_id
polls/urls.py
#_*_coding:utf8_*_
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
使用
<pk>
代替<question_id>
会更加灵活,<pd>
代表主键
相应的视图也需要修改成另一种写法,vote方法保持原样,用于比较两种写法的不同
polls/views.py
#_*_coding:utf8_*_
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
# ...
入门教程不会对代码进入深入的讲解,先大致了解其作用即可,后续再逐个模块进行解析
如果对django2.0教程感兴趣,请关注我的简书,持续更新中...
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有