原文链接
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就重复出来了。重复过程中遇到了很多不懂的代码,先不管了,争取把完整的教程重复完!