博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django表单
阅读量:4920 次
发布时间:2019-06-11

本文共 2212 字,大约阅读时间需要 7 分钟。

新建polls/templates/polls/detail.html

{
{ question.question_text }}

{% if error_message %}

{ { error_message }}

{% endif %}
{% csrf_token %} {% for choice in question.choice_set.all %}
{% endfor %}

 

新建polls/templates/polls/results.html

{
{ question.question_text }}

    {% for choice in question.choice_set.all %}
  • { { choice.choice_text }} -- { { choice.votes }} vote{ { choice.votes|pluralize }}
  • {% endfor %}
Vote again?

 

修改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('
/', views.DetailView.as_view(), name='detail'), # 示例:/polls/5/ path('
/results/', views.ResultsView.as_view(), name='results'), # 示例:/polls/5/results/ path('
/vote/', views.vote, name='vote'), # 示例:/polls/5/vote/ ]

 

python manage.py runserver

启动服务

转载于:https://www.cnblogs.com/yjlch1016/p/8707773.html

你可能感兴趣的文章
命令行解析函数
查看>>
iterm2快捷键启动
查看>>
LeetCode Reverse Nodes in k-Group
查看>>
Todo list and 学习心得
查看>>
html笔记1
查看>>
uva10487-最接近的和
查看>>
FPGA--I2C串行通信总线
查看>>
服务器老是出现502 Bad Gateway?
查看>>
博客系统-点赞取消
查看>>
sql 优化(转)
查看>>
Oracle 迁移 序列
查看>>
弹窗组价
查看>>
小程序の填坑指北
查看>>
AutoMutex
查看>>
13 -1 BOM和定时器
查看>>
uuid.go
查看>>
c#中怎么删除一个非空目录
查看>>
selenium java-2 chrome driver与对应版本
查看>>
javascript的私有机制
查看>>
arguments对象疑惑
查看>>