1. 环境搭建
Django 版本 | Python 版本 |
---|
2.2 | 3.5,3.6,3.7,3.8(2.2.8 添加),3.9(2.2.17 添加) | 3.1 | 3.6,3.7,3.8,3.9(3.1.3 添加) | 3.2 | 3.6, 3.7, 3.8, 3.9, 3.10 (在 3.2.9 中就已经加入了) | 4.0, 4.1 | 3.8,3.9,3.10 |
参考:https://docs.djangoproject.com/zh-hans/4.1/faq/install/#faq-python-version-support
安装django正式发布版
python -m pip install Django
查看django版本
python -m django --version
创建django项目
django-admin startproject django_learn
项目结构
.
├── django_learn
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
- asgi.py 项目的运行在( ASGI 兼容的) Web 服务器上的入口 如何使用 ASGI 来部署
- wsgi.py 项目的运行在 (WSGI 兼容的)Web服务器上的入口 如何使用 WSGI 进行部署
- manage.py 管理django项目命令 命令详情
- url.py url路径声明
- settings.py 配置项目数据库等 详情
项目运行到0.0.0.0:8080
python manage.py runserver 0:8080
2. 快速开发
在manage.py同级目录创建app
python manage.py startapp myapp
settings.py注册app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
settings.py配置允许访问的地址
ALLOWED_HOSTS = ['*']
views.py
from django.http import HttpResponse
def index(request):
return HttpResponse('hello world')
myapp目录下新建urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
django_learn/urls.py 新增app目录下的urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls'))
]
启动项目,访问 http://127.0.0.1:8080/myapp/
urlpatterns使用方式
3. 数据库使用
以mysql为例(参考:https://docs.djangoproject.com/zh-hans/4.1/ref/databases/#mysql-notes)
安装mysql相关依赖(以ubuntu为例,其他环境参考:https://pypi.org/project/mysqlclient)
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
pip install mysqlclient
在settings.py配置mysql数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_learn',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
ENGINE配置其他数据库
'django.db.backends.postgresql'
'django.db.backends.sqlite3'
'django.db.backends.oracle'
自定义表对象myapp/models.py
from django.db import models
class Subject(models.Model):
"""
科目
"""
name = models.CharField(max_length=50, verbose_name='科目名')
create_time = models.DateTimeField(verbose_name='创建时间')
update_time = models.DateTimeField(blank=True, null=True, verbose_name='更新时间')
is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')
class Meta:
db_table = 'tb_subject'
class Student(models.Model):
"""
学生
"""
name = models.CharField(max_length=50, verbose_name='学生名')
age = models.IntegerField(verbose_name='年龄')
create_time = models.DateTimeField(verbose_name='创建时间')
update_time = models.DateTimeField(blank=True, null=True, verbose_name='更新时间')
is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')
sid = models.ForeignKey(Subject, on_delete=models.DO_NOTHING, db_column='sid', verbose_name='科目id')
class Meta:
db_table = 'tb_student'
- db_table:配置表名
- on_delete:配置外键关联删除
- verbose_name:字段在后台系统显示的名称
执行迁移
python manage.py makemigrations myapp
修改的内容被保存到myapp/migrations/0001_initial.py
查看对应的sql语句
python manage.py sqlmigrate myapp 0001
--
-- Create model Subject
--
CREATE TABLE `tb_subject` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(50) NOT NULL, `create_time` datetime(6) NOT NULL, `update_time` datetime(6) NULL, `is_delete` bool NOT NULL);
--
-- Create model Student
--
CREATE TABLE `tb_student` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(50) NOT NULL, `age` integer NOT NULL, `create_time` datetime(6) NOT NULL, `update_time` datetime(6) NULL, `is_delete` bool NOT NULL, `sid` bigint NOT NULL);
ALTER TABLE `tb_student` ADD CONSTRAINT `tb_student_sid_c066e3db_fk_tb_subject_id` FOREIGN KEY (`sid`) REFERENCES `tb_subject` (`id`);
确认无误后迁移到数据库
pyhton manage.py migrate
view.py
def get_subject(request):
subjects = Subject.objects.all()
data = [{'name': s.name} for s in subjects]
return HttpResponse(data)
def set_subject(request):
name = request.GET['name']
subjects = Subject()
subjects.name = name
subjects.create_time = datetime.datetime.now()
subjects.save()
return HttpResponse('ok')
- request.GET:获取请求参数
- Subject.objects.all():查询tb_subject表所有数据
url.py
path('stu/get_subject', views.get_subject, name='get_subject'),
path('stu/set_subject', views.set_subject, name='set_subject'),
访问浏览器
http://0.0.0.0:8080/myapp/stu/set_subject?name=语文
http://0.0.0.0:8080/myapp/stu/set_subject?name=数学
http://0.0.0.0:8080/myapp/stu/get_subject
4. 后台管理系统
创建超级用户
python manage.py createsuperuser
注册subject对象 myapp/admin.py
from django.contrib import admin
from myapp.models import Subject
admin.site.register(Subject)
|