App
创建一个app :
python manage.py startapp app01
admin:
from django.contrib import admin
# Register your models here.
apps:
from django.apps import AppConfig
class App01Config(AppConfig):
name = 'app01'
models.py结合与ORM相关:
from django.db import models
# Create your models here.
test是单元测试用:
from django.test import TestCase
# Create your tests here.
views写视图函数:
from django.shortcuts import render
# Create your views here.
settings-apps:
INSTALLED_APPS = [
'django.contrib.admin', #系统内置app
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"app01.apps.App01Config", #手动注册app
]
apps-config-ready方法重写:
from django.apps import AppConfig
class App01Config(AppConfig):
name = 'app01'
def ready(self):
print("aaa")
ready方法重写:Tools-run manage.py Task:
导入视图函数里面的功能:
from app01 import views
模块点功能:
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^modal/', views.modal),
url(r'^login/', views.login),
]
form表单提交数据:
-
form的属性 method='post' action='地址'
-
input框要有name属性 option要有value值
-
要有一个button按钮或者 input type=‘submit’
提交POST请求注释一个中间件
MIDDLEWARE = [
# 'django.middleware.csrf.CsrfViewMiddleware', # 注释掉可以提交post请求
]
ORM
对象关系映射
Django使用MySQL数据库的流程:
-
创建一个MySQL数据库;
-
配置settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'day43',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD': '123',
}
} -
替换模块
import pymysql
pymysql.install_as_MySQLdb() -
创建表
class User(models.Model):
username = models.CharField(max_length=32) # varchar(32)
password = models.CharField(max_length=32) # varchar(32) -
执行数据库迁移的命令
python manage.py makemigrations # 制作迁移文件
python manage.py migrate # 执行SQL语句 同步迁移
ORM的操作:
all
models.User.objects.all() # 获取所有的数据
get
models.User.objects.get(password='dsb') # 对象 特点 获取不到或者获取到多个都报错
filter
models.User.objects.filter(password='dsb') # 对象列表
create
obj = models.Publisher.objects.create(name=pub_name)
delete
models.Publisher.objects.filter(pk=pk).delete() # 对象列表
models.Publisher.objects.get(pk=pk).delete() # 对象
obj.name = pub_name # 内存中修改属性
obj.save() # 提交保存
models.Publisher.objects.filter(pk=pk).update(name=pub_name)