1:在一个文件夹下使用以下命令创建一个工程为mysite:
django-admin startproject myproject
2.在工程下新建一个app,名为app01:
首先 cd myproject
python manage.py startapp app01
3.django默认有一个后台,可以看到工程下的urls.py(负责将url模式映射到应用程序)文件生成时就有一条路由
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
要登陆后台,必须在工程中注册应用,即在settings.py文件中将上面创建的APP,也就是app01添加进来:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
4.在我们新建的app01目录下models.py中,新建的类就是一张表,打开myproject/app01/models.py 文件进行添加类(也就是添加表):
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(decimal_places=2,max_digits=8)
建了一个名为Book的表,表中有两项:title,price
5.admin后台注册表,修改app01中的admin.py文件:把models创建的表添加到admin后台中去
from django.contrib import admin
# Register your models here.
from app01 import models
admin.site.register(models.Book)
6.接着在终端输入以下命令:
python manage.py makemigrations
python manage.py migrate
这两条命令输入结束后,会在django的工程目录下生成一个名字为db.sqlite3的文件,这就是我们的数据库。
备注:
第一条命令是将我们对models.py文件的改动保存到当前目录中一个叫makemigrations的文件夹中,但未同步到数据库。
第二条命令将改动同步到数据库。
从上图中可以看出,Django默认会以APP名为数据表前缀,以类名为数据表名!
创建的字段如下图:
从上图可以看出,Django会默认加上一个id字段,该字段为主键且自增长
7.django自带有一个web后台,可以使用以下命令创建web后台的用户名和密码
python manage.py createsuperuser
(venv) F:\python_study\djangoProject>python manage.py createsuperuser
Username (leave blank to use 'huangzhengwu'): huangzhengwu
Error: Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters.
Username (leave blank to use 'huangzhengwu'): huangzhengwu
Error: Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters.
Username (leave blank to use 'huangzhengwu'): mingxia66
Email address: m13691685308@163.com
Password:
Password (again):
The password is too similar to the username.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
8.启动django,直接在终端中输入以下命令
python manage.py runserver
启动成功,如下图
(venv) F:\python_study\djangoProject>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
November 20, 2021 - 10:59:10
Django version 3.2.9, using settings 'djangoProject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
9.访问django后台,在浏览器中输入 http://127.0.0.1:8000/admin/
输入上面创建的用户名和密码,即可登录后台
参考链接:
https://blog.csdn.net/wzzzj/article/details/112789956
https://www.cnblogs.com/ginvip/p/6894690.html
https://www.cnblogs.com/yangmv/p/5327477.html