文章目录
准备工作
新建项目
pycharm专业版才有的功能,
删除创建项目自带template,使用创建app生成的
pycharm 自动执行力python manage.py
直接写startapp appname
创建app注册
数据库
创建数据库
create database bm;
写配置文件
settings.py
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
import pymysql
pymysql.install_as_MySQLdb()
# 链接数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bm',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '3306'
}
}
设计表结构
models.py
from django.db import models
class Department(models.Model):
# 部门表
title = models.CharField(verbose_name="标题", max_length=32)
class Userinfo(models.Model):
# 员工表
name = models.CharField(verbose_name="姓名", max_length=32)
password = models.CharField(verbose_name="密码", max_length=64)
age = models.IntegerField(verbose_name="年龄")
account = models.DecimalField(verbose_name="余额", max_digits=10, decimal_places=2)
time = models.DateTimeField(verbose_name="入职时间")
depart = models.Foreignkey(to="Department", to_field="id", on_delete=models.CASCADE)
gender_choices = ((1, "男"),(2, "女"))
gender = models.SmallIntegerField(verbose_name="性别",choices=gender_choices)
depart = models.Foreignkey(to=“Department”, to_field=“id”, on_delete=models.CASCADE)
0.无约束
depart_id = models.BigIntegerField (verbose_name=“部门ID”)
1.有约束
- to,与那张表关联
- to_field,表中的那一列关联
depart = models.Foreignkey(to=“Department”, to_field=“id”) --报错
2.django自动
- 写的虽然是depart
- django自动生成数据列depart_id
3.部门表被删除
3.1级联删除
depart = models.Foreignkey(to=“Department”, to_field=“id”, on_delete=models.CASCADE)
3.2置空
depart = models.ForeignKey (to=“Department”, to_field=“id” , null=True,blank=True, on_delete=models.SET_NULL)
gender_choices = ((1, “男”),(2, “女”))
gender = models.SmallIntegerField(verbose_name=“性别”,choices=gender_choices)
数据库中存储1/2,获取到的是男/女
生成数据库
执行
python3 manage.py makemigrations
python3 manage.py migrate
或者
在这直接执行
makemigrations
migrate
静态文件
基本工作
在urls.py
from bm01 import views
path('dlist/', views.dlist),
views.py
from bm01.models import Department
def dlist(request):
# 部门列表
return render(request, 'dlist.html')
dlist.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'plugins/bootstrap/css/bootstrap.css'%}">
</head>
<body>
<script src="{% static 'js/jquery-3.4.1.js' %}"></script>
<script src="{% static 'plugins/bootstrap/js/bootstrap.js'%}"
</body>
</html>
关键部分
每部分功能按照
- url.py
- views.py
- xxx.html展开
展示
path('dlist/', views.dlist),
from django.shortcuts import render, redirect
from bm01 import