3. 投票 案例项目(合集)
3.投票-1创建项目和子应用
创建项目
- 命令
$ python django-admin startproject mysite
- 目录结构
mysite/ # 项目容器、可任意命名manage.py # 命令行工具mysite/ # 纯 Python 包 # 你引用任何东西都要用到它__init__.py # 空文件 告诉Python这个目录是Python包settings.py # Django 项目配置文件urls.py # URL 声明 # 就像网站目录asgi.py # 部署时用的配置 # 运行在ASGI兼容的Web服务器上的 入口wsgi.py # 部署时用的配置 # 运行在WSGI兼容的Web服务器上的
- 初始化数据库 迁移
$ python mangae.py makemigrations$ python manage.py migrate
Django 简易服务器
用于开发使用,Django 在网络框架方面很NB, 但在网络服务器方面不行~
专业的事让专业的程序做嘛,最后部署到 Nginx Apache 等专业网络服务器上就行啦。
自动重启服务器
对每次访问请求、重新载入一遍 Python 代码
新添加文件等一些操作 不会触发重启
命令
$ python manage.py runserver
E:\PYTHON\0CODE\mysite> E:\PYTHON\0CODE\mysite>python manage.py runserver Watching for file changes with StatReloader Performing system checks...System check identified no issues (0 silenced). June 29, 2022 - 22:35:10 Django version 4.0.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
指定端口
$ python manage.py runserver 8080
创建应用
- 命令
$ python manage.py startapp polls
- 目录结构
polls/__init__.pyadmin.pyapps.pymigrations/__init__.pymodels.pytests.pyviews.py
编写应用视图
- 视图函数
# polls/views.pyfrom django.shortcuts import render# Create your views here.from django.http import HttpResposedef index(rquest):return HttpResponse("投票应用 -首页")
配置路由
配置路由
# polls/urls.py 子应用路由from django.urls import pathfrom . import viewsurlpatterns = [path('', views.index, name='index'), ]
# mysite/urls.py 全局路由 include()即插即用from django.contrib import admin from django.urls import include, pathurlpatterns = [path('polls/', include('polls.urls')),path('admin/', admin.site.urls), ]
效果
path() 参数含义
path('', views.index, name='index'),
path('polls/', include('polls.urls'))
route 路径
一个匹配URL的规则,类似正则表达式。不匹配GET、POST传参 、域名
view 视图函数
Django 调用这个函数,默认传给函数一个 HttpRequest 参数
kwargs 视图函数参数
字典格式
name 给这条URL取一个温暖的名子~
可以在 Django 的任意地方唯一的引用。允许你只改一个文件就能全局地修改某个 URL 模式。
3.投票-2本地化和数据库API
本地化配置
时区和语言
# mysite/mysite/settings.py# Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/LANGUAGE_CODE = 'zh-hans' # 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_TZ = True
为啥要在数据库之前?
配置时区,数据库可以以此做相应配置。比如时间的存放是以UTC还是本地时间...
数据库配置
- django 支持 sqlite mysql postgresql oracle
- 默认是sqlite 它是本地的一个文件name 哪里直接写了文件的绝对路径
# mysite/mysite/settings.py# Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databasesDATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3','NAME': BASE_DIR / 'db.sqlite3',} }
- 迁移 主要为Django默认的模型建表
python manage.py migrate
创建模型
编写
# mysite/polls/models.pyfrom django.db import modelsclass Question(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField('date published')class Choice(models.Model):question = models.ForeignKey(Question, on_delete=models.CASCADE)choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)
很多数据库的知识 都可以用到里面
Question Choice 类都是基于models.Model, 是它的子类。
类的属性--------表的字段
类名-----------表名
还有pub_date on_delete=models.CASCAD 级联删除, pub_date 的字段描述, vo tes的默认值, 都和数据库很像。
而且max_length这个个字段,让Django可以在前端自动校验我们的数据
激活模型
把配置注册到项目
# mysite/mysite/settings.py# Application definitionINSTALLED_APPS = ['polls.apps.PollsConfig','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles', ]
做迁移-
仅仅把模型的配置信息转化成 Sql 语言
(venv) E:\PYTHON\0CODE\mysite>python manage.py makemigrations polls Migrations for 'polls':polls\migrations\0001_initial.py- Create model Question- Create model Choice
查看 Sql 语言 (对应我们配的 Sqlite 数据库的语法)
(venv) E:\PYTHON\0CODE\mysite>python manage.py sqlmigrate polls 0001
BEGIN;
---- Create model Question--CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_data" datetime NOT NULL
);
---- Create model Choice--CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "quest
ion_id" bigint NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
- 执行迁移
(venv) E:\PYTHON\0CODE\mysite>python manage.py migrate Operations to perform:Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations:Applying polls.0001_initial... OK(venv) E:\PYTHON\0CODE\mysite>
API 的初体验
- 进入shell
python manage.py shell
- 增
- (venv) E:\PYTHON\0CODE\mysite>python manage.py shell Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> >>> from polls.models import Question, Choice >>> from django.utils import timezone >>> >>> q = Question( question_text = "what's up ?", pub_date=timezone.now() ) >>> >>> q.save() >>>
- 查看字段
>>> q.id 1 >>> q.question_text "what's up ?" >>> >>> q.pub_date datetime.datetime(2022, 7, 6, 5, 46, 10, 997140, tzinfo=datetime.timezone.utc) >>>
- 改
>>> q.question_text = 'are you kidding me ?' >>> q.save() >>> >>> q.question_text 'are you kidding me ?' >>>>>> >>> >>> Question.objects.all() <QuerySet [<Question: Question object (1)>]> >>> >>>
下面写点更人性化的方法
__str__
方法默认打印自己的text字段,便于查看
后台展示对象数据也会用这个字段
class Question(models.Model):...def __str__(self):return self.question_textclass Choice(models.Model):...def __str__(self):return self.choice_text
- 自定义方法
class Question(models.Model):...def was_published_recently(self):return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
__str__
方法效果(venv) E:\PYTHON\0CODE\mysite>python manage.py shell Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> >>> from polls.models import Question, Choice >>> >>> Question.objects.all() <QuerySet [<Question: are you kidding me ?>]> >>> >>> Question.objects.filter(id=1) <QuerySet [<Question: are you kidding me ?>]> >>>
按属性查
>>> >>> Question.objects.filter(question_text__startswith='are') <QuerySet [<Question: are you kidding me ?>]> >>>>>> from django.utils import timezone >>> >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: are you kidding me ?> >>>>>> Question.objects.get(id=2) Traceback (most recent call last):File "<console>", line 1, in <module>File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_methodreturn getattr(self.get_queryset(), name)(*args, **kwargs)File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\query.py", line 496, in getraise self.model.DoesNotExist( polls.models.Question.DoesNotExist: Question matching query does not exist. >>> >>>
更多操作
用pk找更保险一些,有的model 不以id 为主键
>>> Question.objects.get(pk=1) <Question: are you kidding me ?> >>> # 自定义查找条件 >>> q = Question.objects.get(pk=1) >>> q.was_published_recently() True >>># 安主键获取对象 >>> q = Question.objects.get(pk=1) >>> q.choice_set.all() <QuerySet []> >>># 增 问题对象关系到选项对象 >>> q.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> >>> >>> q.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> >>> >>> q.choice_st.create(choice_text='Just hacking agin', votes=0) Traceback (most recent call last):File "<console>", line 1, in <module> AttributeError: 'Question' object has no attribute 'choice_st' >>> >>> q.choice_set.create(choice_text='Just hacking agin', votes=0) <Choice: Just hacking agin> >>> >>> >>> c = q.choice_set.create(choic_text='Oh my god.', votes=0) Traceback (most recent call last):File "<console>", line 1, in <module>File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 747, in createreturn super(RelatedManager, self.db_manager(db)).create(**kwargs)File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_methodreturn getattr(self.get_queryset(), name)(*args, **kwargs)File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\query.py", line 512, in createobj = self.model(**kwargs)File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\base.py", line 559, in __init__raise TypeError( TypeError: Choice() got an unexpected keyword argument 'choic_text' >>># 选项 关系 到问题 >>> c = q.choice_set.create(choice_text='Oh my god.', votes=0) >>> >>> c.question <Question: are you kidding me ?> >>> >>> q.choice_set.all() <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking agin>, <Choice: Oh my god.>]> >>> >>> >>> q.choice_set.count() 4 >>> >>> Choice.objects.filter(question__pub_date__year=current_year) <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking agin>, <Choice: Oh my god.>]> >>> >>>
删
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete() (1, {'polls.Choice': 1}) >>> >>> q.choice_set.all() <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Oh my god.>]> >>> >>>
管理页面
- 创建用户
(venv) E:\PYTHON\0CODE\mysite>python manage.py createsuperuser用户名: admin 电子邮件地址: admin@qq.com Password: Password (again): 密码长度太短。密码必须包含至少 8 个字符。 这个密码太常见了。 Bypass password validation and create user anyway? [y/N]: y Superuser created successfully.
- 启动 开发服务器
python manage.py runserver
- login
http://localhost:8000/admin/
- 让我们的polls 投票应用也展示在后台
# mysite/polls/admin.pyfrom .models import Question, Choiceadmin.site.register(Question) admin.site.register(Choice)
3.投票-3模板和路由
编写更多视图
# polls/views.py...def detail(request, question_id):return HttpResponse(f"当前问题id:{question_id}")def results(request, question_id):return HttpResponse(f"问题id:{question_id}的投票结果")def vote(request, question_id):return HttpResponse(f"给问题id:{question_id}投票")
添加url
- 全局我们已经加过
urlpatterns = [path('admin/', admin.site.urls),path('polls/', include('polls.urls')),]
- 应用程序添加如下
# polls/urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [path('', views.index, name='index'),path('<int:question_id>/', views.detail, name='detail'),path('<int:question_id>/results/', views.results, name='results'),path('<int:question_id>/vote/', views.vote, name='vote'), ]
看看效果
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
- 从mysite/settings.py 载入
升级index 视图 展示近期5个投票问题
编写视图
def index(request):latest_question_list = Question.objects.order_by('-pub_date')[:5]output = ','.join([q.question_text for q in latest_question_list])return HttpResponse(output)
好吧,总共就一个
加点
这里直接把页面内容,写到了视图函数里,写死的。很不方便,下面用模板文件来处理这个问题
模板文件
- 创建polls存放 模板文件的 文件夹 为什么里面多套了一层polls?没看出他有区分的作用,第一个polls不已经区分过了?
polls/templates/polls/
- 主要内容
# polls/templates/polls/index.html{% if latest_question_list %}<ul>{% for question in latest_question_list %}<li><a href="/polls/{{ question.id }}/">{{question.question_text}}</a></li>{% endfor %}</ul> {% else %}<p>暂时没有开放的投票。</p> {% endif %}
修改视图函数
这里函数载入index.html模本,还传给他一个上下文字典context,字典把模板里的变量映射成了Python 对象
# polls/views.py... from django.template import loaderdef index(request):latest_question_list = Question.objects.order_by('-pub_date')[:5]template = loader.get_template('polls/index.html')context = {'latest_question_list': latest_question_list,}return HttpResponse(template.render(context, request))...
效果
快捷函数 render()
上面的视图函数用法很普遍,有种更简便的函数替代这一过程
# polls/views.py ... from django.template import loaderimport django.shortcuts import renderdef index(request):latest_question_list = Question.objects.order_by('-pub_date')[:5]#template = loader.get_template('polls/index.html')context = {'latest_question_list': latest_question_list,}#return HttpResponse(template.render(context, request))return render(request, 'polls/index.html', context)...
优雅的抛出 404
修改 detail 视图函数
# polls/views.py...def detail(request, question_id):try:question = Question.objects.get(pk=question_id)except:raise Http404("问题不存在 !")# return HttpResponse(f"当前问题id:{question_id}")return render(request, 'polls/detail.html', {'question': question})
编写模板
# polls/templates/polls/detail.html{{ question }}
效果
快捷函数 get_object_or_404()
# polls/views.py from django.shortcuts import render, get_object_or_404...def detail(request, question_id):question = get_object_or_404(Question, pk=question_id)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()
# polls/templates/polls/detail.html<h1>{{ question.question_text }}</h1> <ul>{% for choice in question.choice_set.all %}<li>{{ choice.choice_text }}</li>{% endfor %} </ul>
- 效果
去除 index.html里的硬编码
- 其中的'detail' 使我们在urls.py 定义的名称
# polls/urls.pypath('<int:question_id>/', views.detail, name='detail'),
# polls/templates/polls/index.html<!--<li>--> <!-- <a href="/polls/{{ question.id }}/">{{question.question_text}}</a>--> <!--</li>--><li><a href="{% url 'detail' question.id %}">{{question.question_text}}</a> </li>
- 有啥用?
简单明了 书写方便
我们修改.html 的真实位置后, 只需在urls.py 同步修改一条记录, 就会在所有模板文件的无数个连接中生效
大大的节省时间
为URL添加命名空间
为什么?
上面去除硬链接方便了我们。我们只有1个应用polls有自己的detail.html模板,但有多个应用同时有名字为detail.html的模板时呢?
Django看到{% url %} 咋知道是哪个应用呢?
怎么加 ?
# polls/urls.pyapp_name = 'polls'...
修改.html模板文件
# polls/templates/polls/index.html<!--<li>--> <!-- <a href="/polls/{{ question.id }}/">{{question.question_text}}</a>--> <!--</li>--><!--<li>--> <!-- <a href="{% url 'detail' question.id %}">{{question.question_text}}</a>--> <!--</li>--><li><a href="{% url 'polls:detail' question.id %}">{{question.question_text}}</a> </li>
3.投票-4投票结果保存 和 Django通用模板
投票结果保存
前端
# polls/templates/polls/detail.html{#<h1>{{ question.question_text }}</h1>#}
{#<ul>#}
{# {% for choice in question.choice_set.all %}#}
{# <li>{{ choice.choice_text }}</li>#}
{# {% endfor %}#}
{#</ul>#}<form action="{% url 'polls:vote' question.id %}" method="post">{% csrf_token %}<fieldset>...</fieldset><input type="submit" value="投票">
</form>
# polls/templates/polls/detail.html<form action="{% url 'polls:vote' question.id %}" method="post">{% csrf_token %}<fieldset><legend><h1>{{ question.question_text }}</h1></legend>{% if error_message %}<strong><p>{{ error_message }}</p></strong>{% endif %}{% 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>{% endfor %}</fieldset><input type="submit" value="投票">
</form>
路由
# polls/urls.pypath('<int:question_id>/vote/', views.vote, name='vote'),
视图
vote
# polls/views.py¶# ...from django.http import HttpResponseRedirect
from django.urls import reverse# ...# def vote(request, question_id):
# return HttpResponse(f"给问题id:{question_id}投票")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 += 1selected_choice.save()# 重定向到其他页面 防止误触重复投票return HttpResponse(reverse('polls:results', args=(question.id, )))
result
# polls/views.py¶from django.shortcuts import get_object_or_404, renderdef results(request, question_id):question = get_object_or_404(Question, pk=question_id)return render(request, 'polls/results.html', {'question': question})
前端
新建文件
# 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 %}">继续投票</a>
降低冗余 URLConf
修改url
# mysite/polls/urls.pyfrom django.urls import pathfrom . import viewsapp_name = 'polls'# urlpatterns = [
#
# path('', views.index, name='index'),
#
# path('<int:question_id>/', views.detail, name='detail'),
#
# path('<int:question_id>/results/', views.results, name='results'),
#
# path('<int:question_id>/vote/', views.vote, name='vote'),
#
#
# ]urlpatterns = [path('', views.IndexView.as_view(), name='index'),path('<int:pk>/', views.DeatilView.as_view(), name='detail'),path('<int:pl>/results/', views.ResultsViews.as_view(), name='results'),path('<int:question_id>/vote/', views.vote, name='vote')
]
修改视图
ListView 和 DetailView 。这两个视图分别抽象“显示一个对象列表”和“显示一个特定类型对象的详细信息页面”这两种概念。
每个通用视图需要知道它将作用于哪个模型。 这由 model 属性提供。
template_name 属性是用来告诉 Django 使用一个指定的模板名字,而不是自动生成的默认名字。
自动生成的 context 变量是 question_list。为了覆盖这个行为,我们提供 context_object_name 属性,表示我们想使用 latest_question_list。作为一种替换方案,
# polls/views.pyfrom django.urls import reverse
# ...# def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
#
# template = loader.get_template('polls/index.html')
# context = {
# 'latest_question_list': latest_question_list,
# }
#
# return HttpResponse(template.render(context, request))# 用Django 通用视图 重写index, detail, results视图class IndexView(generic.ListView):template_name = 'polls/index.html'context_object_name = 'latest_question_list'def get_queryset(self):"""返回最近的 5 个投票问题"""return Question.objects.order_by('-pub_date')[:5]class DetailView(generic.DetailView):model = Questiontemplate_name = 'polls/detail.html'class ResultsView(generic.DetailView):model = Questiontemplate_name = 'polls/detail.html'# def detail(request, question_id):
# # try:
# # question = Question.objects.get(pk=question_id)
# #
# # except:
# # raise Http404("问题不存在 !")
#
# # return HttpResponse(f"当前问题id:{question_id}")
#
# question = get_object_or_404(Question, pk=question_id)
# return render(request, 'polls/detail.html', {'question': question})
#
#
# # def results(request, question_id):
# # return HttpResponse(f"问题id:{question_id}的投票结果")
#
# 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):
# return HttpResponse(f"给问题id:{question_id}投票")
3.投票-5自动化测试 模型
自动化测试
一个bug
当设定发布时间为很远的未来的时间时,函数.was_published_recently()竟然返回True
$ python manage.py shell>>> import datetime
>>> from django.utils import timezone
>>> from polls.models import Question
>>> # create a Question instance with pub_date 30 days in the future
>>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30))
>>> # was it published recently?
>>> future_question.was_published_recently()
True
编写测试用例
针对上面的bug写个脚本,用来测试这个bug
# polls/tests.pyimport datetimefrom django.test import TestCase
from django.utils import timezonefrom .models import Questionclass QuestionModelTests(TestCase):def test_was_published_recently_with_future_question(self):"""was_published_recently() returns False for questions whose pub_dateis in the future."""time = timezone.now() + datetime.timedelta(days=30)future_question = Question(pub_date=time)self.assertIs(future_question.was_published_recently(), False)
我们创建了一个 django.test.TestCase 的子类,并添加了一个方法,此方法创建一个 pub_date 时未来某天的 Question 实例。然后检查它的 was_published_recently() 方法的返回值——它 应该 是 False。
运行
# python manage.py test polls
(venv) E:\PYTHON\0CODE\mysite>
(venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_was_published_recently_with_future_questsion (polls.tests.QuestionModelTests)
当日期为 未来 时间时 was_published_recently() 应该返回 False
----------------------------------------------------------------------
Traceback (most recent call last):File "E:\PYTHON\0CODE\mysite\polls\tests.py", line 16, in test_was_published_recently_with_future_questsiontime = timezone.now() + datetime.timedelta(day=30)
TypeError: 'day' is an invalid keyword argument for __new__()----------------------------------------------------------------------
Ran 1 test in 0.001sFAILED (errors=1)
Destroying test database for alias 'default'...(venv) E:\PYTHON\0CODE\mysite>
修复Bug
限制下界为当前
# mysite/polls/models.py#...class Question(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField('date published')def __str__(self):return self.question_text# def was_published_recently(self):## return self.pub_date >= timezone.now()-datetime.timedelta(days=1)def was_published_recently(self):now = timezone.now()# 发布时间比现在小 比一天之前大 (即最近一天发布)return now - datetime.timedelta(days=1) <= self.pub_date <= now#...
测试其他时间段情况
class QuestionModelTests(TestCase):def test_was_published_recently_with_future_question(self):"""当日期为 未来 时间时 was_published_recently() 应该返回 False"""time = timezone.now() + datetime.timedelta(days=30)future_question = Question(pub_date=time)self.assertIs(future_question.was_published_recently(), False)def test_was_published_recently_with_recent_question(self):"""当日期为 最近 时间时 was_published_recently() 应该返回 False"""time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)future_question = Question(pub_date=time)self.assertIs(future_question.was_published_recently(), True)def test_was_published_recently_with_old_question(self):"""当日期为 过去(至少一天前) 时间时 was_published_recently() 应该返回 False"""time = timezone.now() + datetime.timedelta(days=1, seconds=1)future_question = Question(pub_date=time)self.assertIs(future_question.was_published_recently(), False)
运行
Microsoft Windows [版本 10.0.22000.978]
(c) Microsoft Corporation。保留所有权利。
(venv) E:\PYTHON\0CODE\mysite>python manage.py polls test
Unknown command: 'polls'
Type 'manage.py help' for usage.(venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
Found 3 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
----------------------------------------------------------------------
Ran 3 tests in 0.002sOK
Destroying test database for alias 'default'...(venv) E:\PYTHON\0CODE\mysite>
3.投票-6自动化测试 视图
Client 一个工具
这个很像我之前学过的,requests
但他更细节更贴合Django的视图,它可以直接捕获视图函数传过来的参数
Microsoft Windows [版本 10.0.22000.978]
(c) Microsoft Corporation。保留所有权利。(venv) E:\PYTHON\0CODE\mysite>python manage.py shell
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
>>>
>>> from django.test.utils import setup_test_environment
>>>
>>> setup_test_environment()
>>>
>>>
>>> from django.test import Client
>>>
>>> client = Client()
>>>
>>> r = client.get('/')
Not Found: /
>>>
>>> r.status_code
404
>>>
>>> from django.urls import reverse
>>>
>>> r = client.get(reverse("polls:index"))
>>>
>>> r .status_code
200
>>>
>>>
>>>
>>>
>>>
>>> r.content
b'\n <ul>\n \n <li>\n <a href="/polls/5/">Django is nice?</a>\n </li>\n \n <li>\n <a href="/polls/4/">I love Lisa.</a>\n </li>\n \
n <li>\n <a href="/polls/3/">do you lik ch best?</a>\n </li>\n \n <li>\n <a href="/polls/2/">are you okay?</a>\n </li>\n \n <li
>\n <a href="/polls/1/">are you kidding me ?</a>\n </li>\n \n </ul>\n\n'
>>>
>>>
>>>
>>>
>>>
>>> r.context['latest_question_list']
<QuerySet [<Question: Django is nice?>, <Question: I love Lisa.>, <Question: do you lik ch best?>, <Question: are you okay?>, <Question: are you kidding me ?>]>
>>>
>>>
一个 Bug
按照逻辑,当投票发布时间是未来时,视图应当忽略这些投票
修复 Bug
# polls/views.pyclass IndexView(generic.ListView):template_name = 'polls/index.html'context_object_name = 'latest_question_list'def get_queryset(self):"""返回最近的 5 个投票问题"""#return Question.objects.order_by('-pub_date')[:5]return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
测试用例
写个投票脚本,用于产生数据
# polls/test.pydef create_question(question_text, days):"""一个公用的快捷函数用于创建投票问题"""time = timezone.now() + datetime.timedelta(days=days)return Question.objects.create(question_text=question_text, pub_date=time)
测试类
class QuestionIndexViewTests(TestCase):def test_no_questions(self):"""不存在 questions 时候 显示"""res = self.client.get(reverse('polls:index'))self.assertEqual(res.status_code, 200)#self.assertContains(res, "没有【正在进行】的投票。") # 是否显示“没有【正在进行】的投票。”字样self.assertQuerysetEqual(res.context['latest_question_list'], [])def test_past_question(self):"""发布时间是 past 的 question 显示到首页"""question = create_question(question_text="Past question.", days=-30)res = self.client.get(reverse("polls:index"))self.assertQuerysetEqual(res.context['latest_question_list'],[question],)def test_future_question(self):"""发布时间是 future 不显示"""create_question(question_text="未来问题!", days=30)res = self.client.get(reverse('polls:index'))#self.assertContains(res, "没有【可用】的投票")self.assertQuerysetEqual(res.context['latest_question_list'], [])def test_future_question_and_past_question(self):"""存在 past 和 future 的 questions 仅仅显示 past"""question = create_question(question_text="【过去】问题!", days=-30)create_question(question_text="【未来】问题!", days=30)response = self.client.get(reverse('polls:index'))self.assertQuerysetEqual(response.context['latest_question_list'],[question],)def test_two_past_question(self):"""首页可能展示 多个 questions"""q1 = create_question(question_text="过去 问题 1", days=-30)q2 = create_question(question_text="过去 问题 2", days=-5)res = self.client.get(reverse('polls:index'))self.assertQuerysetEqual(res.context['latest_question_list'],[q2, q1],)
运行
(venv) E:\PYTHON\0CODE\mysite>
(venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
Found 8 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
........
----------------------------------------------------------------------
Ran 8 tests in 0.030sOK
Destroying test database for alias 'default'...(venv) E:\PYTHON\0CODE\mysite>
3.投票-7自动化测试 业务逻辑
一个bug
发布日期时未来的那些投票不会在目录页 index 里出现,但是如果用户知道或者猜到正确的 URL ,还是可以访问到它们。所以我们得在 DetailView 里增加一些约束:
修复
加强限制,搜寻结果只返回时间小于当前的投票
# polls/views.pyclass DetailView(generic.DetailView): ...def get_queryset(self):"""Excludes any questions that aren't published yet."""return Question.objects.filter(pub_date__lte=timezone.now())
测试用例
检验
# polls/tests.pyclass QuestionDetailViewTests(TestCase):def test_future_question(self):"""The detail view of a question with a pub_date in the futurereturns a 404 not found."""future_question = create_question(question_text='Future question.', days=5)url = reverse('polls:detail', args=(future_question.id,))response = self.client.get(url)self.assertEqual(response.status_code, 404)def test_past_question(self):"""The detail view of a question with a pub_date in the pastdisplays the question's text."""past_question = create_question(question_text='Past Question.', days=-5)url = reverse('polls:detail', args=(past_question.id,))response = self.client.get(url)self.assertContains(response, past_question.question_text)
3.投票-8应用的界面和风格
a 标签
新建 mysite/polls/static 目录 ,写入下面的文件
static/ #框架会从此处收集所有子应用静态文件 所以需要建一个新的polls目录区分不同应用polls/ #所以写一个重复的polls很必要 否则Django直接使用找到的第一个style.cssstyle.css
定义 a 标签
# /style.cssli a{color: green;
}
背景图
新建 images 目录
static/ #框架会从此处收集所有子应用静态文件 所以需要建一个新的polls目录区分不同应用polls/style.css images/bg.jpg
定义 背景
# /style.cssli a{color: green;
}body {background: white url("images/bg.jpg") no-repeat;
}
效果
3.投票-9自定义后台表单
字段顺序
替换注释部分
# /mysite/polls/templates/admin.py# admin.site.register(Question)class QuestionAdmin(admin.ModelAdmin):fields = ['question_text', 'pub_date'] # 列表里的顺序 表示后台的展示顺序admin.site.register(Question,QuestionAdmin)
效果
字段集
当字段比较多时,可以把多个字段分为几个字段集
注意变量 fields 变为 fieldsets
class QuestionAdmin(admin.ModelAdmin):#fields = ['question_text', 'pub_date'] # 列表里的顺序 表示后台的展示顺序fieldsets = [(None, {'fields': ['question_text']}),('日期信息', {'fields': ['pub_date']}),]
效果
关联选项
这样可以在创建 question 时 同时创建 choice
# /mysite/polls/templates/admin.py
效果
让卡槽更紧凑
替换 StackedInline 为 TabularInline
#class ChoiceInline(admin.StackedInline):
class ChoiceInline(admin.TabularInline):model = Choiceextra = 3 # 默认有三个卡槽 后面还可以点击增加
效果
展示question的更多字段
Django默认返回模型的 str 方法里写的内容
添加字段 list_display 让其同时展示更多
方法was_published_recently
和他的返回内容 也可以当做字段展示
# mysite/polls/templates/admin.py# class QuestionAdmin(admin.ModelAdmin):
# # fields = ['question_text', 'pub_date'] # 列表里的顺序 表示后台的展示顺序
# fieldsets = [
# (None, {'fields': ['question_text']}),
# ('日期信息', {'fields': ['pub_date']}),# ]# inlines = [ChoiceInline] # 引用模型list_display = ('question_text', 'pub_date', 'was_published_recently')
效果 点击还可以按照该字段名排序
3.投票-9自定义后台表单-2
用装饰器优化 方法 的显示
方法 was_published_recently 默认用空格替换下划线展示字段
用装饰器优化一下
# /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)) <= self.pub_date <= now
效果
添加过滤器
添加一个 list_filter 字段即可
# mysite/polls/templates/admin.py# class QuestionAdmin(admin.ModelAdmin):
# # fields = ['question_text', 'pub_date'] # 列表里的顺序 表示后台的展示顺序
# fieldsets = [
# (None, {'fields': ['question_text']}),
# ('日期信息', {'fields': ['pub_date']}),# ]# inlines = [ChoiceInline] # 引用模型# list_display = ('question_text', 'pub_date', 'was_published_recently')list_filter = ['pub_date'] # 过滤器
效果
检索框
同上
#...
search_fields = ['question_text', 'pub_date'] # 检索框 可添加多个字段
效果
3.投票-10自定义后台风格界面
改掉 'Django 管理'
自定义工程模板(就是在manage.py的同级目录哪里)
再建一个templates
/mysite/templates # 新建
修改 mysite/settings.py DIR是一个待检索路径 在django启动时加载
把所有模板文件存放在同一个templates中也可以 但分开会方便以后扩展复用代码
#...# TEMPLATES = [
# {
# 'BACKEND': 'django.template.backends.django.DjangoTemplates',#'DIRS': [],'DIRS': [BASE_DIR / 'templates'],
# 'APP_DIRS': True,
# 'OPTIONS': {
# 'context_processors': [
# 'django.template.context_processors.debug',
# 'django.template.context_processors.request',
# 'django.contrib.auth.context_processors.auth',
# 'django.contrib.messages.context_processors.messages',
# ],
# },
# },
# ]
新建一个admin文件夹 复制 base_site.html 复制到里面
base_site.html 是django默认的模板 它存放在 django/contrib/admin/templates
的 admin/base_site.html
里面
可以用 ...\> py -c "import django; print(django.__path__)"
命令查找源文件django位置
/mysite/templates # 新建/admin # 新建base_site.html # 本地是到E:\PYTHON\0CODE\StudyBuddy\venv\Lib\site-packages\# django\contrib\admin\templates\admin 复制
修改 base_site.html 内容
<!--{% extends "admin/base.html" %}--><!--{% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}--><!--{% block branding %}-->
<!--<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>-->
<h1 id="site-name"><a href="{% url 'admin:index' %}">投票 管理</a></h1>
<!--{% endblock %}--><!--{% block nav-global %}{% endblock %}-->
效果
注意,所有的 Django 默认后台模板均可被复写。若要复写模板,像你修改 base_site.html 一样修改其它文件——先将其从默认目录中拷贝到你的自定义目录,再做修改
当然 也可以用 django.contrib.admin.AdminSite.site_header 来进行简单的定制。
自定义 子应用 的模板
机智的同学可能会问: DIRS 默认是空的,Django 是怎么找到默认的后台模板的?因为 APP_DIRS 被置为 True,Django 会自动在每个应用包内递归查找 templates/ 子目录(不要忘了 django.contrib.admin 也是一个应用)。
我们的投票应用不是非常复杂,所以无需自定义后台模板。不过,如果它变的更加复杂,需要修改 Django 的标准后台模板功能时,修改 应用 的模板会比 工程 的更加明智。这样,在其它工程包含这个投票应用时,可以确保它总是能找到需要的自定义模板文件。
更多关于 Django 如何查找模板的文档,参见 加载模板文档。
自定义 后台 首页的模板
同之前base_site.html
复制 E:\PYTHON\0CODE\StudyBuddy\venv\Lib\site-packages\django\contrib\admin\templates\admin\index.html
到mysite/templates/admin/index.html
直接修改
结束 撒花! :)
3. 投票 案例项目(合集)相关推荐
- 送福利啦!PaddleCV方向精选项目合集
百度大脑AI Studio经过一年的建设, 现在已经积累了数以万计的内容和项目, 为了便于大家学习了解PaddleCV开发技术, AI Studio项目小组特别制作汇总了一批PaddleCV精选项目~ ...
- CVPR 2019 论文和开源项目合集(Papers with Code)
CVPR 2019 论文开源项目合集 传送门:CVPR 2020 论文开源项目合集 附:530 篇 CVPR 2019 论文代码链接 目标检测 目标跟踪 语义分割 实例分割 GAN 人脸检测 人体姿态 ...
- CVPR 2020 论文和开源项目合集(Papers with Code)
CVPR 2020 论文开源项目合集,同时欢迎各位大佬提交issue,分享CVPR 2020开源项目 [推荐阅读] CVPR 2020 virtual ECCV 2020 论文开源项目合集来了:htt ...
- CVPR 2021 论文和开源项目合集(Papers with Code)
摘自:https://github.com/amusi/CVPR2021-Papers-with-Code CVPR 2021 论文和开源项目合集 CVPR 2021 论文和开源项目合集(Papers ...
- Node.js脚本项目合集(一):Node.js+FFmpeg实现批量从B站导出离线缓存视频到mp4格式,mp4转mp3,实现听歌自由
Node.js脚本项目合集(一):Node.js+FFmpeg实现批量从B站导出离线缓存视频到mp4格式,mp4转mp3,实现听歌自由 前言 一.准备工作以及介绍 1.什么是FFmpeg 2.FFmp ...
- 精心为学弟学妹整理的 C语言/C++ 项目合集
C语言/C++ 是一门实践性很强的课程.如果只看书,不做上机练习,相当于纸上谈兵. 很多小伙伴经常问"有什么项目推荐?" ,今天推荐一些. 1.C语言/C++ 入门项目合集 夯实 ...
- 数据分析项目-合集-day02
数据分析项目-合集-day02 需求: - 导入文件,查看原始数据 - 将人口数据和各州的简称数据进行合并 - 将合并的数据中重复的abbreviation进行删除 - 查看存在缺失数据的列 - 找到 ...
- 55 个 Linux 练手项目合集,打通你的 Linux 任督二脉 !
说在前头:无论你是通过上面的楼+课程,在老师带领下系统地学习 Linux,还是通过下面的练手教程,自主学习,我们都希望你能够坚持,一步一步来,别怕重复. 关于这50个练手项目:学习任何语言,最终都是通 ...
- ECCV 2020开源项目合集 (ECCV 2020 paper list with code/data)
文章转载自https://www.paperdigest.org/2020/08/eccv-2020-papers-with-code-data/,如有侵权,留言后删除. 以下表格列出了ECCV 20 ...
- 最全Java项目合集(附源码课件),可完美运行
当今时代是飞速发展的信息时代.在各行各业中离不开信息处理,而有信息处理就离不开信息管理系统,这使得信息管理系统被广泛应用于各领域 其中系统设计是一个把软件需求转换成用软件系统表示的过程.通过对目标系统 ...
最新文章
- QFIL工具如何导出手机分区数据
- 博图v15.1 安装步骤
- 乐高ev3涉及到的一些赛事_使您成为英雄的前五名开发者技能(提示:涉及LEGO)
- 大数据之统计学基础(一)
- MySQL空间索引简单使用
- 电子科技大学《图论及其应用》复习总结--第六章 平面图
- 深度置信网络(DBM)
- RDO方式安装Openstack Allinone问题记录
- 普莱费尔密码(playfair)
- 软件测试周刊(第08期):大过节的
- 发际线与程序员的暧昧关系
- 要实现无人机的乌托邦 阿西莫夫机器人三大定律该变了
- aecmap快捷键_ArcGIS编辑操作的常用快捷键
- html表格填充随页面大小自动缩放,一个简单的html表格自适应解决方案
- 利用VBA在EXCEL 获取网页上的天气
- 被开了!!!!!!!!!!
- 2021年危险化学品经营单位安全管理人员考试内容及危险化学品经营单位安全管理人员考试试卷
- 对N行N列二维数组的每一行排序,偶数行(0当作偶数)由小到大排序,奇数行由大到小排序
- 【数据分享】第六次、第七次人口普查深圳各街道数据
- 超实用!移动端界面中的版式设计原理(下)