常用命令
python manage.py runserver 0.0.0.0
python manage.py startapp appname
python manage.py syncdb
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
django-admin startproject mysite
配置文件
配置模板文件
TEMPLATE_DIRS = (
os.path.join(BASE_DIR,'templates'),
)
配置静态文件
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
路由系统
基于正则的路由
注意:两种正则的路由,只能同时使用一种,不能混用
# 路由系统
urlpatterns = [
url(r'^index1/(d+)/(d+)', index1),
url(r'^index1/(?P<n1>d+)/(?P<n2>d+)', index2),
]
# views函数
def index1(request,a1,a2):
print("----",a1,"-----",a2,"-------")
return HttpResponse("from index1")
# 注意:
def index2(request,n1,n2):
print("----",n1,"=====",n2,"-------")
return HttpResponse("from index1")
路由分发
# 主站
from django.conf.urls import include
urlpatterns = [
url(r'^app01/', include("app01.urls")),
url(r'^app02/', include("app02.urls")),
]
# 分发路由
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^index.html$', views.index),
]
# 127.0.0.1:8080/app01/index.html
路由设置别名
Model中使用获取URL 自定义get_absolute_url() 方法
模板中使用生成URL {% url 'h2' 2012 %}
用于反生成url
# project/urls.py
from django.urls import reverse
# reverse根据别名,反生成URL
# views函数
def index(request,a1):
user_list=["zou","run","cheng"]
v = reverse("n1",args=(123456,))
print(v) # /index/123456
return HttpResponse("...")
# 路由系统
urlpatterns = [
url(r'^index/(d+)', index,name="n1"),
]
配置数据库
1.在Mysql中创建数据库
2.在settings中配置DATABASE
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'s4day70db',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 3306,
}
}
3.在与project同名的init下修改django中默认连接数据库的方式
import pymysql
pymysql.install_as_MySQLdb()
4.在settings.py中注册app01
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
5.运行命令创建数据表
python manage.py makemigrations
python manage.py migrate
ORM增删改查
from django.shortcuts import render,HttpResponse
from app01 import models
def index(request):
# 增
models.UserGroup.objects.create(title="研发部")
models.UserInfo.objects.create(username="alex",password="123",age=18,ug_id=1)
# 查
# filter(id=1)的结果是[obj,]
# filter(id=1).first()的结果是obj
group_list = models.UserGroup.objects.all()
group_list = models.UserGroup.objects.filter(id__gt=2)
group_list = models.UserGroup.objects.filter(id=4).first()
for row in group_list:
print(row.id,row.title)
# 删
models.UserGroup.objects.filter(id=7).delete()
# 改
models.UserGroup.objects.filter(id=6).update(title="外交部")
return HttpResponse("hello world")
middleware中间件
在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。在django项目的settings模块中,有一个 MIDDLEWARE.
中间件中可以定义如下方法。
process_request(self,request)
process_view(self, request, callback, callback_args, callback_kwargs)
process_template_response(self,request,response)
process_exception(self, request, exception)
process_response(self, request, response)
以上方法的返回值可以是None和HttpResonse对象,如果是None,则继续按照django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户。
// 撰写中间件
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class Middle1(MiddlewareMixin):
def process_request(self, request):
print("m1.process_request")
def process_response(self, request, response):
print("m1.process_response")
return response
class Middle2(MiddlewareMixin):
def process_request(self, request):
print("m2.process_request")
def process_response(self, request, response):
print("m2.process_response")
return response
//在settings中注册
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"my_middle.Middle1",
"my_middle.Middle2",
]
// 执行结果
//m1.process_request
//m2.process_request
//执行视图函数
//m2.process_response
//m1.process_response
CBV操作
# 1.路由系统
urlpatterns = [
url(r'^login.html$', views.Login.as_view()),
]
# 2.views类
"""
get 查
post 创建
put 更新
delete 删除
"""
# 根据request.method的方式自动执行对应的函数。
# 我们可以重写dispatch函数来实现类似装饰器的效果,dispatch内部根据反射来实现函数执行。
from django.views import View
class Login(View):
def get(self,request):
return render(request, "login.html")
def post(self, request):
name = request.POST.get("user")
print(name)
return HttpResponse("from post ")
def dispatch(self, request, *args, **kwargs):
print("-----before------")
ret = super().dispatch(request,*args,**kwargs)
print("-----after------")
return ret
# # CBV应用装饰器
# django的bug,不能直接对类进行装饰,必须使用 method_decorator,把装饰器当作参数传进去。
from django.utils.decorators import method_decorator
@method_decorator(wrapper, name="post")