1 常用指令
pip install django -i https://pypi.douban.com/simple/ # 使用豆瓣镜像安装 django
django-admin startproject mysite # 创建个人项目
python manage.py runserver # 启动项目
python manage.py startapp polls # 创建投票应用
python manage.py makemigrations # 生成数据库迁移文件
python manage.py migrate # 执行数据库迁移文件
python manage.py createsuperuser # 创建超级账号
2 编写第一个视图
# polls.views
from django.http import HttpResponse
def index(request):
return HttpResponse("你好,欢迎来到投票网站")
# polls.urls
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
# mysite.urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("polls/", include("polls.urls")),
]
访问:http://127.0.0.1:8000/polls/
3 创建 model 类并生成数据库表
# polls.models
from django.db import models
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 makemigrations # 生成数据库迁移文件
python manage.py migrate # 执行数据库迁移文件
使用 shell
命令查看效果:
python manage.py shell # 打开shell 窗口
from polls.models import Choice, Question
Question.objects.all()
# <QuerySet []>
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
# 1
Question.objects.all()
# <QuerySet [<Question: Question object (1)>]>
但是 <QuerySet [<Question: Question object (1)>]>=
好像并没有实际意义,所以可以给 model
加上 __str__
方法:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text
4 创建超级账号
python manage.py createsuperuser
登录:
http://127.0.0.1:8000/admin/
在管理页中加入投票模块:
# polls.admin
from django.contrib import admin
from .models import Question
admin.site.register(Question)
再次访问管理页: