翼度科技»论坛 编程开发 python 查看内容

3. 投票 案例项目(合集)

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
3.投票-1创建项目和子应用

创建项目


  • 命令
    1. $ python django-admin startproject mysite
    复制代码
  • 目录结构
    1. mysite/               # 项目容器、可任意命名
    2.     manage.py         # 命令行工具
    3.     mysite/           # 纯 Python 包 # 你引用任何东西都要用到它
    4.         __init__.py   # 空文件 告诉Python这个目录是Python包
    5.         settings.py   # Django 项目配置文件
    6.         urls.py       # URL 声明  # 就像网站目录
    7.         asgi.py       # 部署时用的配置 # 运行在ASGI兼容的Web服务器上的 入口
    8.         wsgi.py       # 部署时用的配置 # 运行在WSGI兼容的Web服务器上的
    复制代码
  • 初始化数据库 迁移
    1. $ python mangae.py makemigrations
    2. $ python manage.py migrate
    复制代码
Django 简易服务器


  • 用于开发使用,Django 在网络框架方面很NB, 但在网络服务器方面不行~
    专业的事让专业的程序做嘛,最后部署到 Nginx Apache 等专业网络服务器上就行啦。
  • 自动重启服务器
    对每次访问请求、重新载入一遍 Python 代码
    新添加文件等一些操作 不会触发重启
  • 命令
    1. $ python manage.py runserver
    复制代码
    1. E:\PYTHON\0CODE\mysite>
    2. E:\PYTHON\0CODE\mysite>python manage.py runserver
    3. Watching for file changes with StatReloader
    4. Performing system checks...
    5. System check identified no issues (0 silenced).
    6. June 29, 2022 - 22:35:10
    7. Django version 4.0.5, using settings 'mysite.settings'
    8. Starting development server at http://127.0.0.1:8000/
    9. Quit the server with CTRL-BREAK.
    复制代码
  • 指定端口
    1. $ python manage.py runserver 8080
    复制代码
创建应用



  • 命令
    1. $ python manage.py startapp polls
    复制代码
  • 目录结构
    1. polls/
    2.     __init__.py
    3.     admin.py
    4.     apps.py
    5.     migrations/
    6.         __init__.py
    7.     models.py
    8.     tests.py
    9.     views.py
    复制代码

编写应用视图


  • 视图函数
    1. # polls/views.py
    2. from django.shortcuts import render
    3. # Create your views here.
    4. from django.http import HttpRespose
    5. def index(rquest):
    6.     return HttpResponse("投票应用 -首页")
    复制代码
配置路由


  • 配置路由
    1. # polls/urls.py  子应用路由
    2. from django.urls import path
    3. from . import views
    4. urlpatterns = [
    5.     path('', views.index, name='index'),
    6. ]
    复制代码
    1. # mysite/urls.py  全局路由 include()即插即用
    2. from django.contrib import admin
    3. from django.urls import include, path
    4. urlpatterns = [
    5.     path('polls/', include('polls.urls')),
    6.     path('admin/', admin.site.urls),
    7. ]
    复制代码
  • 效果
    <img alt="截图" loading="lazy">



path() 参数含义

  1. path('', views.index, name='index'),
复制代码
  1. path('polls/', include('polls.urls'))
复制代码

  • route 路径
    一个匹配URL的规则,类似正则表达式。不匹配GET、POST传参 、域名
  • view 视图函数
    1. Django 调用这个函数,默认传给函数一个 HttpRequest 参数
    复制代码
  • kwargs 视图函数参数
    字典格式
  • name 给这条URL取一个温暖的名子~
    可以在 Django 的任意地方唯一的引用。允许你只改一个文件就能全局地修改某个 URL 模式。


3.投票-2本地化和数据库API

本地化配置


  • 时区和语言
    1. # mysite/mysite/settings.py
    2. # Internationalization
    3. # https://docs.djangoproject.com/en/4.0/topics/i18n/
    4. LANGUAGE_CODE = 'zh-hans'   # 'en-us'
    5. TIME_ZONE = 'UTC'
    6. USE_I18N = True
    7. USE_TZ = True
    复制代码
  • 为啥要在数据库之前?
    配置时区,数据库可以以此做相应配置。比如时间的存放是以UTC还是本地时间...

数据库配置


  • django 支持 sqlite  mysql  postgresql   oracle
  • 默认是sqlite  它是本地的一个文件name 哪里直接写了文件的绝对路径
    1. # mysite/mysite/settings.py
    2. # Database
    3. # https://docs.djangoproject.com/en/4.0/ref/settings/#databases
    4. DATABASES = {
    5.     'default': {
    6.         'ENGINE': 'django.db.backends.sqlite3',
    7.         'NAME': BASE_DIR / 'db.sqlite3',
    8.     }
    9. }
    复制代码
  • 迁移  主要为Django默认的模型建表
    1. python manage.py migrate
    复制代码
创建模型



  • 编写
    1. # mysite/polls/models.py
    2. from django.db import models
    3. class Question(models.Model):
    4.     question_text = models.CharField(max_length=200)
    5.     pub_date = models.DateTimeField('date published')
    6. class Choice(models.Model):
    7.     question = models.ForeignKey(Question, on_delete=models.CASCADE)
    8.     choice_text = models.CharField(max_length=200)
    9.     votes = models.IntegerField(default=0)
    复制代码
  • 很多数据库的知识  都可以用到里面
    Question  Choice 类都是基于models.Model, 是它的子类。
    类的属性--------表的字段
    类名-----------表名
    还有pub_date on_delete=models.CASCAD 级联删除, pub_date 的字段描述, vo   tes的默认值, 都和数据库很像。
    而且max_length这个个字段,让Django可以在前端自动校验我们的数据
激活模型



  • 把配置注册到项目
    1. # mysite/mysite/settings.py
    2. # Application definition
    3. INSTALLED_APPS = [
    4.     'polls.apps.PollsConfig',
    5.     'django.contrib.admin',
    6.     'django.contrib.auth',
    7.     'django.contrib.contenttypes',
    8.     'django.contrib.sessions',
    9.     'django.contrib.messages',
    10.     'django.contrib.staticfiles',
    11. ]
    复制代码
  • 做迁移-
    仅仅把模型的配置信息转化成 Sql 语言
    1. (venv) E:\PYTHON\0CODE\mysite>python manage.py makemigrations polls
    2. Migrations for 'polls':
    3.   polls\migrations\0001_initial.py
    4.     - Create model Question
    5.     - Create model Choice
    复制代码
    查看 Sql 语言 (对应我们配的 Sqlite 数据库的语法)
  1. (venv) E:\PYTHON\0CODE\mysite>python manage.py sqlmigrate polls 0001
  2. BEGIN;
  3. --
  4.   -- Create model Question
  5.   --
  6.   
  7.   CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_data" datetime NOT NULL
  8. );
  9. --
  10.   -- Create model Choice
  11.   --
  12.   
  13.   CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "quest
  14. ion_id" bigint NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
  15. CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
  16. COMMIT;
  17.   
复制代码

  • 执行迁移
    1. (venv) E:\PYTHON\0CODE\mysite>python manage.py migrate
    2. Operations to perform:
    3.   Apply all migrations: admin, auth, contenttypes, polls, sessions
    4. Running migrations:
    5.   Applying polls.0001_initial... OK
    6. (venv) E:\PYTHON\0CODE\mysite>
    复制代码

API 的初体验



  • 进入shell
    1. python manage.py shell
    复制代码


    1. - (venv) E:\PYTHON\0CODE\mysite>python manage.py shell
    2. Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
    3. Type "help", "copyright", "credits" or "license" for more information.
    4. (InteractiveConsole)
    5. >>>
    6. >>> from polls.models import Question, Choice
    7. >>> from django.utils import timezone
    8. >>>
    9. >>> q = Question( question_text = "what's up ?", pub_date=timezone.now() )
    10. >>>
    11. >>> q.save()
    12. >>>
    复制代码
  • 查看字段
    1. >>> q.id
    2. 1
    3. >>> q.question_text
    4. "what's up ?"
    5. >>>
    6. >>> q.pub_date
    7. datetime.datetime(2022, 7, 6, 5, 46, 10, 997140, tzinfo=datetime.timezone.utc)
    8. >>>
    复制代码
    1. >>> q.question_text = 'are you kidding me ?'
    2. >>> q.save()
    3. >>>
    4. >>> q.question_text
    5. 'are you kidding me ?'
    6. >>>
    7. >>>
    8. >>>
    9. >>> Question.objects.all()
    10. <QuerySet [<Question: Question object (1)>]>
    11. >>>
    12. >>>
    复制代码
下面写点更人性化的方法


  • __str__方法
    默认打印自己的text字段,便于查看
    后台展示对象数据也会用这个字段
    1. class Question(models.Model):
    2.     ...
    3.    
    4.     def __str__(self):
    5.         return self.question_text
    6. class Choice(models.Model):
    7.     ...
    8.    
    9.     def __str__(self):
    10.         return self.choice_text
    复制代码


  • 自定义方法
    1. class Question(models.Model):
    2.     ...
    3.     def was_published_recently(self):
    4.         return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
    复制代码


  • __str__方法效果
    1. (venv) E:\PYTHON\0CODE\mysite>python manage.py shell
    2. Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
    3. Type "help", "copyright", "credits" or "license" for more information.
    4. (InteractiveConsole)
    5. >>>
    6. >>> from polls.models import Question, Choice
    7. >>>
    8. >>> Question.objects.all()
    9. <QuerySet [<Question: are you kidding me ?>]>
    10. >>>
    11. >>> Question.objects.filter(id=1)
    12. <QuerySet [<Question: are you kidding me ?>]>
    13. >>>
    复制代码
  • 按属性查
    1. >>>
    2. >>> Question.objects.filter(question_text__startswith='are')
    3. <QuerySet [<Question: are you kidding me ?>]>
    4. >>>
    5. >>> from django.utils import timezone
    6. >>>
    7. >>> current_year = timezone.now().year
    8. >>> Question.objects.get(pub_date__year=current_year)
    9. <Question: are you kidding me ?>
    10. >>>
    11. >>> Question.objects.get(id=2)
    12. Traceback (most recent call last):
    13.   File "<console>", line 1, in <module>
    14.   File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    15.     return getattr(self.get_queryset(), name)(*args, **kwargs)
    16.   File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\query.py", line 496, in get
    17.     raise self.model.DoesNotExist(
    18. polls.models.Question.DoesNotExist: Question matching query does not exist.
    19. >>>
    20. >>>
    复制代码
  • 更多操作
    用pk找更保险一些,有的model 不以id 为主键
    1. >>> Question.objects.get(pk=1)  
    2. <Question: are you kidding me ?>
    3. >>>
    4. # 自定义查找条件
    5. >>> q = Question.objects.get(pk=1)
    6. >>> q.was_published_recently()
    7. True
    8. >>>
    9. # 安主键获取对象
    10. >>> q = Question.objects.get(pk=1)
    11. >>> q.choice_set.all()
    12. <QuerySet []>
    13. >>>
    14. # 增  问题对象关系到选项对象
    15. >>> q.choice_set.create(choice_text='Not much', votes=0)
    16. <Choice: Not much>
    17. >>>
    18. >>> q.choice_set.create(choice_text='The sky', votes=0)
    19. <Choice: The sky>
    20. >>>
    21. >>> q.choice_st.create(choice_text='Just hacking agin', votes=0)
    22. Traceback (most recent call last):
    23.   File "<console>", line 1, in <module>
    24. AttributeError: 'Question' object has no attribute 'choice_st'
    25. >>>
    26. >>> q.choice_set.create(choice_text='Just hacking agin', votes=0)
    27. <Choice: Just hacking agin>
    28. >>>
    29. >>>
    30. >>> c = q.choice_set.create(choic_text='Oh my god.', votes=0)
    31. Traceback (most recent call last):
    32.   File "<console>", line 1, in <module>
    33.   File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 747, in create
    34.     return super(RelatedManager, self.db_manager(db)).create(**kwargs)
    35.   File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    36.     return getattr(self.get_queryset(), name)(*args, **kwargs)
    37.   File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\query.py", line 512, in create
    38.     obj = self.model(**kwargs)
    39.   File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\base.py", line 559, in __init__
    40.     raise TypeError(
    41. TypeError: Choice() got an unexpected keyword argument 'choic_text'
    42. >>>
    43. # 选项 关系 到问题
    44. >>> c = q.choice_set.create(choice_text='Oh my god.', votes=0)
    45. >>>
    46. >>> c.question
    47. <Question: are you kidding me ?>
    48. >>>
    49. >>> q.choice_set.all()
    50. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking agin>, <Choice: Oh my god.>]>
    51. >>>
    52. >>>
    53. >>> q.choice_set.count()
    54. 4
    55. >>>
    56. >>> Choice.objects.filter(question__pub_date__year=current_year)
    57. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking agin>, <Choice: Oh my god.>]>
    58. >>>
    59. >>>
    复制代码
    1. >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
    2. >>> c.delete()
    3. (1, {'polls.Choice': 1})
    4. >>>
    5. >>> q.choice_set.all()
    6. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Oh my god.>]>
    7. >>>
    8. >>>
    复制代码

管理页面



  • 创建用户
    1. (venv) E:\PYTHON\0CODE\mysite>python manage.py createsuperuser
    2. 用户名: admin
    3. 电子邮件地址: admin@qq.com
    4. Password:
    5. Password (again):
    6. 密码长度太短。密码必须包含至少 8 个字符。
    7. 这个密码太常见了。
    8. Bypass password validation and create user anyway? [y/N]: y
    9. Superuser created successfully.
    复制代码
  • 启动 开发服务器
    1. python manage.py runserver
    复制代码
  • login
    1. http://localhost:8000/admin/
    复制代码
  • 让我们的polls 投票应用也展示在后台
    1. # mysite/polls/admin.py
    2. from .models import Question, Choice
    3. admin.site.register(Question)
    4. admin.site.register(Choice)
    复制代码
3.投票-3模板和路由

编写更多视图

  1. # polls/views.py
  2. ...
  3. def detail(request, question_id):
  4.    
  5.     return HttpResponse(f"当前问题id:{question_id}")
  6. def results(request, question_id):
  7.    
  8.     return HttpResponse(f"问题id:{question_id}的投票结果")
  9. def vote(request, question_id):
  10.    
  11.     return HttpResponse(f"给问题id:{question_id}投票")
复制代码
添加url


  • 全局我们已经加过
    1. urlpatterns = [
    2.     path('admin/', admin.site.urls),
    3.     path('polls/', include('polls.urls')),
    4.    
    5. ]
    复制代码


  • 应用程序添加如下
    1. # polls/urls.py
    2. from django.urls import path
    3. from . import views
    4. urlpatterns = [
    5.     path('', views.index, name='index'),
    6.     path('<int:question_id>/', views.detail, name='detail'),
    7.     path('<int:question_id>/results/', views.results, name='results'),
    8.     path('<int:question_id>/vote/', views.vote, name='vote'),
    9. ]
    复制代码

看看效果


  • path 里的参数很敏感  结尾含/ 的访问时也必须含 / 否则404





  • 以 /polls/1/ 为例分析匹配过程

    • 从mysite/settings.py 载入 ROOT_URLCONF = 'mysite.urls'
    • 从urls.py 的“polls/”匹配到 polls/  载入 polls.urls
    • 从polls/urls.py  的“int:question_id/”匹配到 1/ ,获取int型的 1 转发给视图函数 views.details



升级index 视图  展示近期5个投票问题


  • 编写视图
    1. def index(request):
    2.     latest_question_list = Question.objects.order_by('-pub_date')[:5]
    3.     output = ','.join([q.question_text for q  in latest_question_list])
    4.     return HttpResponse(output)
    复制代码
  • 好吧,总共就一个

  • 加点


这里直接把页面内容,写到了视图函数里,写死的。很不方便,下面用模板文件来处理这个问题

模板文件


  • 创建polls存放 模板文件的 文件夹   为什么里面多套了一层polls?没看出他有区分的作用,第一个polls不已经区分过了?
    1. polls/templates/polls/
    复制代码
  • 主要内容
    1. # polls/templates/polls/index.html
    2. {% if latest_question_list %}
    3.   <ul>
    4.     {% for question in latest_question_list %}
    5.         <li>
    6.           <a target="_blank" href="https://www.cnblogs.com/polls/{{ question.id }}/">{{question.question_text}}</a>
    7.         </li>
    8.     {% endfor %}
    9.   </ul>
    10. {% else %}
    11.     <p>暂时没有开放的投票。</p>
    12. {% endif %}
    复制代码


  • 修改视图函数
    这里函数载入index.html模本,还传给他一个上下文字典context,字典把模板里的变量映射成了Python 对象
    1. # polls/views.py
    2. ...
    3. from django.template import loader
    4. def index(request):
    5.     latest_question_list = Question.objects.order_by('-pub_date')[:5]
    6.     template = loader.get_template('polls/index.html')
    7.     context = {
    8.         'latest_question_list': latest_question_list,
    9.     }
    10.     return HttpResponse(template.render(context, request))
    11.    
    12. ...
    复制代码
  • 效果



  • 快捷函数 render()
    上面的视图函数用法很普遍,有种更简便的函数替代这一过程
    1. # polls/views.py
    2. ...
    3. from django.template import loader
    4. import django.shortcuts import render
    5. def index(request):
    6.     latest_question_list = Question.objects.order_by('-pub_date')[:5]
    7.     #template = loader.get_template('polls/index.html')
    8.     context = {
    9.         'latest_question_list': latest_question_list,
    10.     }
    11.     #return HttpResponse(template.render(context, request))
    12.     return render(request, 'polls/index.html', context)
    13.    
    14. ...
    复制代码

优雅的抛出 404


  • 修改 detail 视图函数
    1. # polls/views.py
    2. ...
    3. def detail(request, question_id):
    4.     try:
    5.         question = Question.objects.get(pk=question_id)
    6.     except:
    7.         raise Http404("问题不存在 !")
    8.     # return HttpResponse(f"当前问题id:{question_id}")
    9.     return render(request, 'polls/detail.html', {'question': question})
    复制代码
  • 编写模板
    1. # polls/templates/polls/detail.html
    2. {{ question }}
    复制代码
  • 效果

  • 快捷函数   get_object_or_404()
    1. # polls/views.py
    2. from django.shortcuts import render, get_object_or_404
    3. ...
    4. def detail(request, question_id):
    5.    
    6.     question = get_object_or_404(Question, pk=question_id)
    7.     return render(request, 'polls/detail.html', {'question': question})
    复制代码


  • 效果


使用模板系统


  • 对detail.html获取的question变量进行分解 展示

    • 模板系统用.来访问变量属性
    • 如question.question_text先对question用字典查找nobj.get(str)------>属性查找obj.str---------->列表查找obj[int]当然在第二步就成功的获取了question_text属性,不在继续进行。
    • 其中 question.choice_set.all解释为Python代码question.choice_set.all()
    1. # polls/templates/polls/detail.html
    2. <h1>{{ question.question_text }}</h1>
    3. <ul>
    4.     {% for choice in question.choice_set.all %}
    5.         <li>{{ choice.choice_text }}</li>
    6.     {% endfor %}
    7. </ul>
    复制代码
  • 效果



去除 index.html里的硬编码



  • 其中的'detail' 使我们在urls.py 定义的名称
    1. # polls/urls.py
    2. path('<int:question_id>/', views.detail, name='detail'),
    复制代码
    1. # polls/templates/polls/index.html
    2. <li>
    3.        <a target="_blank" href="https://www.cnblogs.com/{% url 'detail' question.id %}">{{question.question_text}}</a>
    4. </li>
    复制代码
  • 有啥用?

    • 简单明了 书写方便
    • 我们修改.html 的真实位置后, 只需在urls.py 同步修改一条记录, 就会在所有模板文件的无数个连接中生效
      大大的节省时间

为URL添加命名空间



  • 为什么?
    上面去除硬链接方便了我们。我们只有1个应用polls有自己的detail.html模板,但有多个应用同时有名字为detail.html的模板时呢?
    Django看到{% url %} 咋知道是哪个应用呢?
  • 怎么加 ?
    1. # polls/urls.py
    2. app_name = 'polls'
    3. ...
    复制代码
  • 修改.html模板文件
    1. # polls/templates/polls/index.html
    2. <li>
    3.        <a target="_blank" href="https://www.cnblogs.com/{% url 'detail' question.id %}">{{question.question_text}}</a>
    4. </li>
    复制代码
3.投票-4投票结果保存 和 Django通用模板

投票结果保存


前端
  1. # polls/templates/polls/detail.html
  2. {#<h1>{{ question.question_text }}</h1>#}
  3. {#<ul>#}
  4. {#    {% for choice in question.choice_set.all %}#}
  5. {#        <li>{{ choice.choice_text }}</li>#}
  6. {#    {% endfor %}#}
  7. {#</ul>#}
  8. <form action="{% url 'polls:vote' question.id %}" method="post">
  9.     {% csrf_token %}
  10.     <fieldset>
  11.    
  12.         ...
  13.         
  14.     </fieldset>
  15.     <input type="submit" value="投票">
  16. </form>
复制代码
  1. # polls/templates/polls/detail.html
  2. <form action="{% url 'polls:vote' question.id %}" method="post">
  3.     {% csrf_token %}
  4.     <fieldset>
  5.         <legend><h1>{{ question.question_text }}</h1></legend>
  6.         {% if error_message  %}
  7.             <strong><p>{{ error_message }}</p></strong>
  8.         {% endif %}
  9.         {% for choice in question.choice_set.all %}
  10.             <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
  11.             <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
  12.         {% endfor %}
  13.     </fieldset>
  14.     <input type="submit" value="投票">
  15. </form>
复制代码
路由
  1. # polls/urls.py
  2. path('<int:question_id>/vote/', views.vote, name='vote'),
复制代码
视图

vote
  1. # polls/views.py¶
  2. # ...
  3. from django.http import HttpResponseRedirect
  4. from django.urls import reverse
  5. # ...
  6. # def vote(request, question_id):
  7. #     return HttpResponse(f"给问题id:{question_id}投票")
  8. def vote(request, question_id):
  9.     question = get_object_or_404(Question, pk=question_id)
  10.     try:
  11.         selected_choice = question.choice_set.get(pk=request.POST['choice'])
  12.     except (KeyError, Choice.DoesNotExist):
  13.         return render(request, 'polls/detail.html', {
  14.             'question': question,
  15.             'error_message': "选择为空, 无法提交 !"
  16.         })
  17.     else:
  18.         selected_choice.votes += 1
  19.         selected_choice.save()
  20.         # 重定向到其他页面 防止误触重复投票
  21.         return HttpResponse(reverse('polls:results', args=(question.id, )))
复制代码
result

  1. # polls/views.py¶
  2. from django.shortcuts import get_object_or_404, render
  3. def results(request, question_id):
  4.     question = get_object_or_404(Question, pk=question_id)
  5.     return render(request, 'polls/results.html', {'question': question})
复制代码

前端

新建文件
  1. # polls/templates/polls/results.html¶
  2. <h1>{{ question.question_text }}</h1>
  3. <ul>
  4.     {% for choice in question.choice_set.all %}
  5.         <li>{{ choice.choice_text }} -- {{ choice.votes }} vote {{ choice.votes|pluralize }}</li>
  6.     {% endfor %}
  7. </ul>
  8. <a target="_blank" href="https://www.cnblogs.com/{% url 'polls:detail' question.id %}">继续投票</a>
复制代码

降低冗余 URLConf

修改url
  1. # mysite/polls/urls.py
  2. from django.urls import path
  3. from . import views
  4. app_name = 'polls'
  5. # urlpatterns = [
  6. #
  7. #     path('', views.index, name='index'),
  8. #
  9. #     path('<int:question_id>/', views.detail, name='detail'),
  10. #
  11. #     path('<int:question_id>/results/', views.results, name='results'),
  12. #
  13. #     path('<int:question_id>/vote/', views.vote, name='vote'),
  14. #
  15. #
  16. # ]
  17. urlpatterns = [
  18.     path('', views.IndexView.as_view(), name='index'),
  19.     path('<int:pk>/', views.DeatilView.as_view(), name='detail'),
  20.     path('<int:pl>/results/', views.ResultsViews.as_view(), name='results'),
  21.     path('<int:question_id>/vote/', views.vote, name='vote')
  22. ]
复制代码
修改视图

ListView 和 DetailView 。这两个视图分别抽象“显示一个对象列表”和“显示一个特定类型对象的详细信息页面”这两种概念。
每个通用视图需要知道它将作用于哪个模型。 这由 model 属性提供。
template_name 属性是用来告诉 Django 使用一个指定的模板名字,而不是自动生成的默认名字。
自动生成的 context 变量是 question_list。为了覆盖这个行为,我们提供 context_object_name 属性,表示我们想使用 latest_question_list。作为一种替换方案,
  1. # polls/views.py
  2. from django.urls import reverse
  3. # ...
  4. # def index(request):
  5. #     latest_question_list = Question.objects.order_by('-pub_date')[:5]
  6. #
  7. #     template = loader.get_template('polls/index.html')
  8. #     context = {
  9. #         'latest_question_list': latest_question_list,
  10. #     }
  11. #
  12. #     return HttpResponse(template.render(context, request))
  13. # 用Django 通用视图 重写index, detail, results视图
  14. class IndexView(generic.ListView):
  15.     template_name = 'polls/index.html'
  16.     context_object_name = 'latest_question_list'
  17.    
  18.     def get_queryset(self):
  19.         """返回最近的 5 个投票问题"""
  20.         return Question.objects.order_by('-pub_date')[:5]
  21.    
  22. class DetailView(generic.DetailView):
  23.     model = Question
  24.     template_name = 'polls/detail.html'
  25. class ResultsView(generic.DetailView):
  26.     model = Question
  27.     template_name = 'polls/detail.html'
  28.    
  29.    
  30. # def detail(request, question_id):
  31. #     # try:
  32. #     #     question = Question.objects.get(pk=question_id)
  33. #     #
  34. #     # except:
  35. #     #     raise Http404("问题不存在 !")
  36. #
  37. #     # return HttpResponse(f"当前问题id:{question_id}")
  38. #
  39. #     question = get_object_or_404(Question, pk=question_id)
  40. #     return render(request, 'polls/detail.html', {'question': question})
  41. #
  42. #
  43. # # def results(request, question_id):
  44. # #     return HttpResponse(f"问题id:{question_id}的投票结果")
  45. #
  46. # def results(request, question_id):
  47. #     question = get_object_or_404(Question, pk=question_id)
  48. #     return render(request, 'polls/results.html', {'question': question})
  49. # def vote(request, question_id):
  50. #     return HttpResponse(f"给问题id:{question_id}投票")
复制代码
3.投票-5自动化测试 模型


自动化测试


一个bug

当设定发布时间为很远的未来的时间时,函数.was_published_recently()竟然返回True
  1. $ python manage.py shell
  2. >>> import datetime
  3. >>> from django.utils import timezone
  4. >>> from polls.models import Question
  5. >>> # create a Question instance with pub_date 30 days in the future
  6. >>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30))
  7. >>> # was it published recently?
  8. >>> future_question.was_published_recently()
  9. True
复制代码
编写测试用例

针对上面的bug写个脚本,用来测试这个bug
  1. # polls/tests.py
  2. import datetime
  3. from django.test import TestCase
  4. from django.utils import timezone
  5. from .models import Question
  6. class QuestionModelTests(TestCase):
  7.     def test_was_published_recently_with_future_question(self):
  8.         """
  9.         was_published_recently() returns False for questions whose pub_date
  10.         is in the future.
  11.         """
  12.         time = timezone.now() + datetime.timedelta(days=30)
  13.         future_question = Question(pub_date=time)
  14.         self.assertIs(future_question.was_published_recently(), False)
复制代码
我们创建了一个 django.test.TestCase 的子类,并添加了一个方法,此方法创建一个 pub_date 时未来某天的 Question 实例。然后检查它的 was_published_recently() 方法的返回值——它 应该 是 False。

运行

  1. # python manage.py test polls
复制代码
  1. (venv) E:\PYTHON\0CODE\mysite>
  2. (venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
  3. Found 1 test(s).
  4. Creating test database for alias 'default'...
  5. System check identified no issues (0 silenced).
  6. E
  7. ======================================================================
  8. ERROR: test_was_published_recently_with_future_questsion (polls.tests.QuestionModelTests)
  9. 当日期为 未来 时间时 was_published_recently() 应该返回 False
  10. ----------------------------------------------------------------------
  11. Traceback (most recent call last):
  12.   File "E:\PYTHON\0CODE\mysite\polls\tests.py", line 16, in test_was_published_recently_with_future_questsion
  13.     time = timezone.now() + datetime.timedelta(day=30)
  14. TypeError: 'day' is an invalid keyword argument for __new__()
  15. ----------------------------------------------------------------------
  16. Ran 1 test in 0.001s
  17. FAILED (errors=1)
  18. Destroying test database for alias 'default'...
  19. (venv) E:\PYTHON\0CODE\mysite>
复制代码




修复Bug

限制下界为当前
  1. # mysite/polls/models.py
  2. #...
  3. class Question(models.Model):
  4.     question_text = models.CharField(max_length=200)
  5.     pub_date = models.DateTimeField('date published')
  6.     def __str__(self):
  7.         return self.question_text
  8.     # def was_published_recently(self):
  9.     #
  10.     #     return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
  11.     def was_published_recently(self):
  12.         now = timezone.now()
  13.         # 发布时间比现在小 比一天之前大 (即最近一天发布)
  14.         return now - datetime.timedelta(days=1) <= self.pub_date <= now
  15.         
  16. #...
复制代码
3.投票-6自动化测试 视图

Client 一个工具

这个很像我之前学过的,requests
但他更细节更贴合Django的视图,它可以直接捕获视图函数传过来的参数
  1. class QuestionModelTests(TestCase):
  2.     def test_was_published_recently_with_future_question(self):
  3.         """
  4.         当日期为 未来 时间时 was_published_recently() 应该返回 False
  5.         """
  6.         time = timezone.now() + datetime.timedelta(days=30)
  7.         future_question = Question(pub_date=time)
  8.         self.assertIs(future_question.was_published_recently(), False)
  9.     def test_was_published_recently_with_recent_question(self):
  10.         """
  11.         当日期为 最近 时间时 was_published_recently() 应该返回 False
  12.         """
  13.         time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
  14.         future_question = Question(pub_date=time)
  15.         self.assertIs(future_question.was_published_recently(), True)
  16.     def test_was_published_recently_with_old_question(self):
  17.         """
  18.         当日期为 过去(至少一天前) 时间时 was_published_recently() 应该返回 False
  19.         """
  20.         time = timezone.now() + datetime.timedelta(days=1, seconds=1)
  21.         future_question = Question(pub_date=time)
  22.         self.assertIs(future_question.was_published_recently(), False)
复制代码

一个 Bug

按照逻辑,当投票发布时间是未来时,视图应当忽略这些投票

修复 Bug

  1. Microsoft Windows [版本 10.0.22000.978]
  2. (c) Microsoft Corporation。保留所有权利。
  3. (venv) E:\PYTHON\0CODE\mysite>python manage.py polls test
  4. Unknown command: 'polls'
  5. Type 'manage.py help' for usage.
  6. (venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
  7. Found 3 test(s).
  8. Creating test database for alias 'default'...
  9. System check identified no issues (0 silenced).
  10. ...
  11. ----------------------------------------------------------------------
  12. Ran 3 tests in 0.002s
  13. OK
  14. Destroying test database for alias 'default'...
  15. (venv) E:\PYTHON\0CODE\mysite>
复制代码
测试用例



写个投票脚本,用于产生数据
  1. Microsoft Windows [版本 10.0.22000.978]
  2. (c) Microsoft Corporation。保留所有权利。
  3. (venv) E:\PYTHON\0CODE\mysite>python manage.py shell
  4. Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
  5. Type "help", "copyright", "credits" or "license" for more information.
  6. (InteractiveConsole)
  7. >>>
  8. >>>
  9. >>> from django.test.utils import setup_test_environment
  10. >>>
  11. >>> setup_test_environment()
  12. >>>
  13. >>>
  14. >>> from django.test import Client
  15. >>>
  16. >>> client = Client()
  17. >>>
  18. >>> r = client.get('/')
  19. Not Found: /
  20. >>>
  21. >>> r.status_code
  22. 404
  23. >>>
  24. >>> from django.urls import reverse
  25. >>>
  26. >>> r = client.get(reverse("polls:index"))
  27. >>>
  28. >>> r .status_code
  29. 200
  30. >>>
  31. >>>
  32. >>>
  33. >>>
  34. >>>
  35. >>> r.content
  36. b'\n  <ul>\n    \n        <li>\n          <a target="_blank" href="https://www.cnblogs.com/polls/5/">Django is nice?</a>\n        </li>\n    \n        <li>\n          <a target="_blank" href="https://www.cnblogs.com/polls/4/">I love Lisa.</a>\n        </li>\n    \
  37. n        <li>\n          <a target="_blank" href="https://www.cnblogs.com/polls/3/">do you lik ch best?</a>\n        </li>\n    \n        <li>\n          <a target="_blank" href="https://www.cnblogs.com/polls/2/">are you okay?</a>\n        </li>\n    \n        <li
  38. >\n          <a target="_blank" href="https://www.cnblogs.com/polls/1/">are you kidding me ?</a>\n        </li>\n    \n  </ul>\n\n'
  39. >>>
  40. >>>
  41. >>>
  42. >>>
  43. >>>
  44. >>> r.context['latest_question_list']
  45. <QuerySet [<Question: Django is nice?>, <Question: I love Lisa.>, <Question: do you lik ch best?>, <Question: are you okay?>, <Question: are you kidding me ?>]>
  46. >>>
  47. >>>
复制代码
测试类
  1. # polls/views.py
  2. class IndexView(generic.ListView):
  3.     template_name = 'polls/index.html'
  4.     context_object_name = 'latest_question_list'
  5.     def get_queryset(self):
  6.         """返回最近的 5 个投票问题"""
  7.         #return Question.objects.order_by('-pub_date')[:5]
  8.         return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
复制代码

运行

  1. # polls/test.py
  2. def create_question(question_text, days):
  3.     """
  4.     一个公用的快捷函数用于创建投票问题
  5.     """
  6.     time = timezone.now() + datetime.timedelta(days=days)
  7.     return Question.objects.create(question_text=question_text, pub_date=time)
复制代码
3.投票-7自动化测试 业务逻辑

一个bug

发布日期时未来的那些投票不会在目录页 index 里出现,但是如果用户知道或者猜到正确的 URL ,还是可以访问到它们。所以我们得在 DetailView 里增加一些约束:

修复

加强限制,搜寻结果只返回时间小于当前的投票
  1. class QuestionIndexViewTests(TestCase):
  2.     def test_no_questions(self):
  3.         """
  4.         不存在 questions 时候 显示
  5.         """
  6.         res = self.client.get(reverse('polls:index'))
  7.         self.assertEqual(res.status_code, 200)
  8.         #self.assertContains(res, "没有【正在进行】的投票。")  # 是否显示“没有【正在进行】的投票。”字样
  9.         self.assertQuerysetEqual(res.context['latest_question_list'], [])
  10.     def test_past_question(self):
  11.         """
  12.         发布时间是 past 的 question 显示到首页
  13.         """
  14.         question = create_question(question_text="Past question.", days=-30)
  15.         res = self.client.get(reverse("polls:index"))
  16.         self.assertQuerysetEqual(
  17.             res.context['latest_question_list'],
  18.             [question],
  19.         )
  20.     def test_future_question(self):
  21.         """
  22.         发布时间是 future 不显示
  23.         """
  24.         create_question(question_text="未来问题!", days=30)
  25.         res = self.client.get(reverse('polls:index'))
  26.         #self.assertContains(res, "没有【可用】的投票")
  27.         self.assertQuerysetEqual(res.context['latest_question_list'], [])
  28.     def test_future_question_and_past_question(self):
  29.         """
  30.         存在 past 和 future 的 questions 仅仅显示 past
  31.         """
  32.         question = create_question(question_text="【过去】问题!", days=-30)
  33.         create_question(question_text="【未来】问题!", days=30)
  34.         response = self.client.get(reverse('polls:index'))
  35.         self.assertQuerysetEqual(
  36.             response.context['latest_question_list'],
  37.             [question],
  38.         )
  39.     def test_two_past_question(self):
  40.         """
  41.         首页可能展示 多个 questions
  42.         """
  43.         q1 = create_question(question_text="过去 问题 1", days=-30)
  44.         q2 = create_question(question_text="过去 问题 2", days=-5)
  45.         res = self.client.get(reverse('polls:index'))
  46.         self.assertQuerysetEqual(
  47.             res.context['latest_question_list'],
  48.             [q2, q1],
  49.         )
复制代码
测试用例

检验
  1. (venv) E:\PYTHON\0CODE\mysite>
  2. (venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
  3. Found 8 test(s).
  4. Creating test database for alias 'default'...
  5. System check identified no issues (0 silenced).
  6. ........
  7. ----------------------------------------------------------------------
  8. Ran 8 tests in 0.030s
  9. OK
  10. Destroying test database for alias 'default'...
  11. (venv) E:\PYTHON\0CODE\mysite>
复制代码
3.投票-8应用的界面和风格

a 标签

新建 mysite/polls/static 目录 ,写入下面的文件
  1. # polls/views.py
  2. class DetailView(generic.DetailView):
  3.     ...
  4.     def get_queryset(self):
  5.         """
  6.         Excludes any questions that aren't published yet.
  7.         """
  8.         return Question.objects.filter(pub_date__lte=timezone.now())
复制代码
定义 a 标签
  1. # polls/tests.py
  2. class QuestionDetailViewTests(TestCase):
  3.     def test_future_question(self):
  4.         """
  5.         The detail view of a question with a pub_date in the future
  6.         returns a 404 not found.
  7.         """
  8.         future_question = create_question(question_text='Future question.', days=5)
  9.         url = reverse('polls:detail', args=(future_question.id,))
  10.         response = self.client.get(url)
  11.         self.assertEqual(response.status_code, 404)
  12.     def test_past_question(self):
  13.         """
  14.         The detail view of a question with a pub_date in the past
  15.         displays the question's text.
  16.         """
  17.         past_question = create_question(question_text='Past Question.', days=-5)
  18.         url = reverse('polls:detail', args=(past_question.id,))
  19.         response = self.client.get(url)
  20.         self.assertContains(response, past_question.question_text)
复制代码

背景图

新建  images 目录
  1. static/        #框架会从此处收集所有子应用静态文件 所以需要建一个新的polls目录区分不同应用
  2.   polls/       #所以写一个重复的polls很必要 否则Django直接使用找到的第一个style.css
  3.     style.css   
  4.    
复制代码
定义 背景
  1. # polls/tests.py
  2. class QuestionDetailViewTests(TestCase):
  3.     def test_future_question(self):
  4.         """
  5.         The detail view of a question with a pub_date in the future
  6.         returns a 404 not found.
  7.         """
  8.         future_question = create_question(question_text='Future question.', days=5)
  9.         url = reverse('polls:detail', args=(future_question.id,))
  10.         response = self.client.get(url)
  11.         self.assertEqual(response.status_code, 404)
  12.     def test_past_question(self):
  13.         """
  14.         The detail view of a question with a pub_date in the past
  15.         displays the question's text.
  16.         """
  17.         past_question = create_question(question_text='Past Question.', days=-5)
  18.         url = reverse('polls:detail', args=(past_question.id,))
  19.         response = self.client.get(url)
  20.         self.assertContains(response, past_question.question_text)body {    background: white url("images/bg.jpg") no-repeat;}
复制代码

效果


3.投票-9自定义后台表单

字段顺序

替换注释部分
  1. static/        #框架会从此处收集所有子应用静态文件 所以需要建一个新的polls目录区分不同应用
  2.   polls/
  3.     style.css   
  4.     images/
  5.       bg.jpg
复制代码
效果


字段集


当字段比较多时,可以把多个字段分为几个字段集
注意变量 fields 变为 fieldsets
  1. # /style.css
  2. li a{
  3.     color: green;
  4. }
  5. body {
  6.     background: white url("images/bg.jpg") no-repeat;
  7. }
复制代码
效果


关联选项

这样可以在创建 question 时 同时创建 choice
# /mysite/polls/templates/admin.py


效果



让卡槽更紧凑

替换 StackedInline 为 TabularInline
  1. # /mysite/polls/templates/admin.py
  2. # admin.site.register(Question)
  3. class QuestionAdmin(admin.ModelAdmin):
  4.     fields = ['question_text', 'pub_date']  # 列表里的顺序 表示后台的展示顺序
  5. admin.site.register(Question,QuestionAdmin)
复制代码
效果


展示question的更多字段


Django默认返回模型的 str 方法里写的内容



添加字段 list_display 让其同时展示更多
方法was_published_recently 和他的返回内容  也可以当做字段展示
  1. class QuestionAdmin(admin.ModelAdmin):
  2.     #fields = ['question_text', 'pub_date']  # 列表里的顺序 表示后台的展示顺序
  3.     fieldsets = [
  4.         (None, {'fields': ['question_text']}),
  5.         ('日期信息', {'fields': ['pub_date']}),
  6.     ]
复制代码
效果  点击还可以按照该字段名排序

3.投票-9自定义后台表单-2

用装饰器优化 方法 的显示

方法 was_published_recently 默认用空格替换下划线展示字段


用装饰器优化一下
[code]# /mysite/polls/templates/models.pyfrom django.contrib import admin  # 装饰器class Question(models.Model):    #....    @admin.display(            boolean=True,            ordering='pub_date',            description='最近发布的吗 ?',        )    def was_published_recently(self):        now = timezone.now()        # 发布时间距离现在不超过24小时 比现在小 比一天之前大 (即最近一天发布)        return (now - datetime.timedelta(days=1))

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

上一篇: python定时器

下一篇: 02-python简介

举报 回复 使用道具