Django表单
新建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 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/templates/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>
修改polls包里面的views.py
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from polls.models import Question, Choice
# Create your views here.
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):
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()
# 成功处理post数据后,始终返回HttpResponseRedirect
# 如果用户点击后退按钮,这将防止两次发布数据。
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
修改polls包里面的polls_urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
# 示例:/polls/
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
# 示例:/polls/5/
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
# 示例:/polls/5/results/
path('<int:question_id>/vote/', views.vote, name='vote'),
# 示例:/polls/5/vote/
]
python manage.py runserver
启动服务