网站开发西安,免费做的英文网站,wordpress 如何修改网页标题,游戏开发物语破解版官方有很详细的文档#xff0c;但是看过几遍之后如果要翻找还是有点麻烦#xff0c;本文算作是学习笔记#xff0c;提取一些关键点记录下来#xff0c;另附上官方教程 编写你的第一个 Django 应用 注#xff1a; 文中的指令使用py#xff0c;是在Windows上#xff0c;ma…官方有很详细的文档但是看过几遍之后如果要翻找还是有点麻烦本文算作是学习笔记提取一些关键点记录下来另附上官方教程 编写你的第一个 Django 应用 注 文中的指令使用py是在Windows上macOS要使用 python3 1. 安装Django
Django 是一个基于 Python 的Web开发框架安装前可以用下面的命令检查是否安装了 Django如果已经安装会显示版本没有安装会提示没有该模块
py -m django --version
如果没有安装可以使用下面的命令安装
py -m pip install Django
2. 创建项目
项目就是一个 project一个项目可以包含多个 app也可以理解为多个模块创建项目使用如下命令其中 mysite 是项目名称
django-admin startproject mysite
在令窗口中切到刚刚创建的项目的根目录有 manage.py在项目中创建一个app名字就叫 polls
py manage.py startapp polls 然后修改几个文件
polls/views.py
from django.http import HttpResponsedef index(request):return HttpResponse(Hello World!)
polls/urls.py
from django.urls import path
from . import viewsurlpatterns [path(, views.index, nameindex),
]
mysite/urls.py
from django.contrib import admin
from django.urls import include, pathurlpatterns [path(polls/, include(polls.urls)),path(admin/, admin.site.urls),
] 最后启动服务浏览器访问 http://localhost:8000/polls/
py manage.py runserver
3. 配置语言和时区
项目配置在 mysite/settings.py
语言标识可以在这里查找 Language Identifiers (RFC 3066)
# 语言设置为中文
LANGUAGE_CODE zh-Hans
时区标识可以在这里查找 List of tz database time zones
# 时区设置为北京时间
TIME_ZONE Asia/Shanghai
4. 数据库
就使用自带的 SQLite 吧方便又简单如果开发商用的Web App建议使用其他数据库要进行额外的配置。
1创建数据模型
修改 polls/models.py
import datetimefrom django.db import models
from django.utils import timezoneclass Question(models.Model):question_text models.CharField(max_length200)pub_date models.DateTimeField(date published)def __str__(self):return self.question_textdef was_published_recently(self):return self.pub_date timezone.now() - datetime.timedelta(days1)class Choice(models.Model):# Choice属于一个Questionquestion models.ForeignKey(Question, on_deletemodels.CASCADE)choice_text models.CharField(max_length200)votes models.IntegerField(default0)def __str__(self):return self.choice_text2激活模型
修改 mysite/settings.py在 INSTALLED_APP 中添加 polls.apps.PollsConfig
INSTALLED_APPS [polls.apps.PollsConfig,django.contrib.admin,django.contrib.auth,django.contrib.contenttypes,django.contrib.sessions,django.contrib.messages,django.contrib.staticfiles,
]
3创建数据迁移(尚未提交)
py manage.py makemigrations polls
查看创建的迁移使用的SQL语句下面命令中的 0001 是上面创建迁移时生成的 polls/migrations/0001_initial.py 文件名中的数字
py manage.py sqlmigrate polls 0001
4提交迁移
py manage.py migrate
总结起来就三步修改模型 - 创建迁移 - 提交迁移 5玩转数据库API
打开交互式窗口
py manage.py shell from polls.models import Choice, QuestionQuestion.objects.all()
QuerySet []from django.utils import timezoneq Question(question_textWhats new?, pub_datetimezone.now())q.save()q.id
1q.question_text
Whats new?q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfodatetime.timezone.utc)q.question_text Whats up?q.save()Question.objects.all()
QuerySet [Question: Question object (1)]from polls.models import Choice, QuestionQuestion.objects.all()
QuerySet [Question: Whats up?]Question.objects.filter(id1)
QuerySet [Question: Whats up?]Question.objects.filter(question_text__startswithWhat)
QuerySet [Question: Whats up?]from django.utils import timezonecurrent_year timezone.now().yearQuestion.objects.get(pub_date__yearcurrent_year)
Question: Whats up?Question.objects.get(id2)
Traceback (most recent call last):...
DoesNotExist: Question matching query does not exist.Question.objects.get(pk1)
Question: Whats up?q Question.objects.get(pk1)q.was_published_recently()
Trueq Question.objects.get(pk1)q.choice_set.all()
QuerySet []q.choice_set.create(choice_textNot much, votes0)
Choice: Not muchq.choice_set.create(choice_textThe sky, votes0)
Choice: The skyc q.choice_set.create(choice_textJust hacking again, votes0)c.question
Question: Whats up? q.choice_set.all()
QuerySet [Choice: Not much, Choice: The sky, Choice: Just hacking again]q.choice_set.count()
3Choice.objects.filter(question__pub_date__yearcurrent_year)
QuerySet [Choice: Not much, Choice: The sky, Choice: Just hacking again]c q.choice_set.filter(choice_text__startswithJust hacking)c.delete() 5. 创建管理员 输入下面的命令然后根据提示设置账户名邮箱密码
py manage.py createsuperuser
启动服务浏览器访问 http://127.0.0.1:8000/admin/
py manage.py runserver 修改 polls/admin.py 让管理员可管理数据
from django.contrib import adminfrom .models import Questionadmin.site.register(Question)
管理员登录后 6. 使用 html 模板
1创建 HTML 文件
在 polls/ 目录下新建一个 templates 文件夹在 polls\templates\ 目录下新建一个 polls 文件见如果新建一个 HTML 文件比如 index.html其最终的路径为 mysite\polls\templates\polls\index.html代码中将使用 polls\index.html
polls\templates\polls\index.html
{% if latest_question_list %}ul{% for question in latest_question_list %}lia href{% url index question.id %}{{ question.question_text }}/a/li{% endfor %}/ul
{% else %}pNo polls are available./p
{% endif %} 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
2配置 view
修改 polls/views.py
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404from .models import Questiondef index(request):latest_question_list Question.objects.order_by(-pub_date)[:5]context {latest_question_list: latest_question_list}return render(request, polls/index.html, context)def detail(request, question_id):question get_object_or_404(Question, pkquestion_id)context {question: question}return render(request, polls/detail.html, context)def results(request, question_id):return HttpResponse(Results)def vote(request, question_id):return HttpResponse(Vote)
3配置 url
修改 polls/urls.py
from django.urls import pathfrom . import viewsurlpatterns [# ex: /polls/path(, views.index, nameindex),# ex: /polls/5/path(int:question_id/, views.detail, namedetail),# ex: /polls/5/results/path(int:question_id/results/, views.results, nameresults),# ex: /polls/5/vote/path(int:question_id/vote/, views.vote, namevote),
]
4URL命名空间
当项目存在多个应用时可能需要借助命名空间来确定url在应用的 urls.py 中配置 app_name
from django.urls import pathfrom . import viewsapp_name polls
urlpatterns [# ex: /polls/path(, views.index, nameindex),# ex: /polls/5/path(int:question_id/, views.detail, namedetail),# ex: /polls/5/results/path(int:question_id/results/, views.results, nameresults),# ex: /polls/5/vote/path(int:question_id/vote/, views.vote, namevote),
]
index.html 中添加 app_name:
{% if latest_question_list %}ul{% for question in latest_question_list %}lia href{% url polls:index question.id %}{{ question.question_text }}/a/li{% endfor %}/ul
{% else %}pNo polls are available./p
{% endif %}
5创建表单 修改 detail.html
form action{% url polls:vote question.id %} methodpost
{% csrf_token %}
fieldsetlegendh1{{ question.question_text }}/h1/legend{% if error_message %}pstrong{{ error_message }}/strong/p{% endif %}{% for choice in question.choice_set.all %}input typeradio namechoice idchoice{{ forloop.counter }} value{{ choice.id }}label forchoice{{ forloop.counter }}{{ choice.choice_text }}/labelbr{% endfor %}
/fieldset
input typesubmit valueVote
/form
表单中涉及投票页面和投票结果页面得新增一个 results.html并修改 views.py
results.html
h1{{ question.question_text }}/h1ul
{% for choice in question.choice_set.all %}li{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}/li
{% endfor %}
/ula href{% url polls:detail question.id %}Vote again?/a
views.py 中修改 results 和 vote 方法
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reversefrom .models import Question, Choicedef index(request):latest_question_list Question.objects.order_by(-pub_date)[:5]context {latest_question_list: latest_question_list}return render(request, polls/index.html, context)def detail(request, question_id):question get_object_or_404(Question, pkquestion_id)context {question: question}return render(request, polls/detail.html, context)def results(request, question_id):question get_object_or_404(Question, pkquestion_id)return render(request, polls/results.html, {question: question})def vote(request, question_id):question get_object_or_404(Question, pkquestion_id)try:selected_choice question.choice_set.get(pkrequest.POST[choice])except (KeyError, Choice.DoesNotExist):return render(request, polls/detail.html,{question: question,error_message: You didnt select a choice.},)else:selected_choice.votes 1selected_choice.save()return HttpResponseRedirect(reverse(polls:results, args(question.id,)))
7. 编写测试用例
首先得有个bug巧了我们的 polls 应用现在就有一个小 bug 需要被修复我们的要求是如果 Question 是在一天之内发布的 Question.was_published_recently() 方法将会返回 True 然而现在这个方法在 Question 的 pub_date 字段比当前时间还晚时也会返回 True这是个 Bug。 在 polls\tests.py 中编写测试代码
import datetimefrom django.test import TestCase
from django.utils import timezone
from .models import Questionclass QuestionModelTests(TestCase):def test_was_published_recently_with_future_question(self):检测异常发布时间比当前时间还要晚time timezone.now() datetime.timedelta(days30)future_question Question(pub_datetime)self.assertIs(future_question.was_published_recently(), False)
运行测试指令是在项目跟目录执行的该目录有 manage.py
py manage.py test polls
py manage.py test polls 将会寻找 polls 应用里的测试代码查找 django.test.TestCase 子类创建一个特殊的数据库供测试使用在类中寻找测试方法——以 test 开头的方法。