Django2.2帮助文档的第一个例子:一个简易的投票系统—Prat1_2
- 2020 年 3 月 3 日
- 筆記
原文链接
https://docs.djangoproject.com/en/2.2/intro/tutorial01/
查看Django版本
python -m Django --version
本份教程使用的Django版本是2.2;Python版本是3.5或者之后(This tutorial is written for Django 2.2, which supports Python 3.5 and later.)
创建项目
django-admin startproject mysite
创建app
python manage.py startapp polls
在新生成的polls文件夹下新建一个urls.py的文件 写上代码
from django.urls import path from . import views urlpatterns = [ path('',views.index,name="index") ]
在当前目录下的views.py文件中写入代码
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index")
在mysite目录下的urls.py文件里写入代码
from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('polls/',include('polls.urls')) ]
运行服务器看下效果
python manager.py runserver
在浏览器里输入 http://127.0.0.1:8000/polls/ 可以看到

image.png
在mysite目录下的settings文件中的INSTALLED_APPS列表中写入‘polls.apps.PollsConfig’ 在polls文件夹下的models.py文件中写入代码
class 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)
在命令行窗口输入
python manage.py migrate python manage.py makemigrations polls python manage.py sqlmigrate polls 0001 python manage.py migrate
更改polls文件夹下的models.py文件
import datetime from django.db import models from django.utils import timezone # Create your models here. 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) class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
在命令行窗口输入
python manage.py shell from polls.models import Choice, Question from django.utils import timezone q = Question(question_text="What's new?", pub_date=timezone.now()) q.save() q.question_text q.pub_date q.question_text = "What's up?" q.save() exit()
创建管理员账户
python manage.py createsuperuser Username: admin Email address: [email protected] Password: ********** Password (again): ********* Superuser created successfully. python manage.py runserver

image.png
至此,教程的part1和part2就重复出来了。重复过程中遇到了很多不懂的代码,先不管了,争取把完整的教程重复完!