Django学习笔记
资料链接
- 视频链接:https://www.bilibili.com/video/BV1vK4y1o7jH
- 笔记链接:https://blog.csdn.net/king_weng/category_11734882.html
- 需要软件:VM, ubantu, django, Pycharm
创建一个页面的流程
- 终端操作:
1)创建项目:django-admin stratproject xxx
2)创建应用:将进入文件夹(不是同名文件夹), python3 manage.py startapp user(用户名)
3)打开数据库:mysql -u root -p(需要su进入超级管理模式)
4)创建数据库:create database xxx default charset utf8
5)启动服务器: python3 manage.py runserver(文件夹下) - Pycharm中:
1)项目打开,项目位置open
2)常规配置(setting.py): ‘应用’ 47行注释
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
# 'NAME': BASE_DIR / 'db.sqlite3',
'NAME': 'xxx',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306'
}
}
3)应用.models.py中 : 模板类,补充输出格式
def __str__(self):
return 'username %s'%(self.username)
-
终端操作
1)同步数据库:python3 manage.py makemigrations 与 python3 manage.py migrate
2)mysql中查看表头内容:use xxx show tables; desc 哪个表 -
Pycharm中:
1)应用.veiw.py中: 加视图函数
def reg_view(request):
if request.method == 'GET':
return render(request, 'user/register.html')
elif request.method == 'POST':
username = request.POST['username']
password_1 = request.POST['password_1']
password_2 = request.POST['password_2']
# 1,两个密码要保持一致并
if password_1 != password_2:
return HttpResponse('error')
#Hash
m = hashlib.md5(password_1.encode("utf8"))
password_m = m.hexdigest()
# 2,当前用户名是否可用, find
old_users = User.objects.filter(username=username)
if old_users:
return HttpResponse('error')
#3,插入数据【明文处理密码】
#拦截多线程错误
try:
user = User.objects.create(username=username, password=password_m )
except Exception as e:
print('--create user errpr')
return HttpResponse('error')
#session更安全 免登录一天
#记录会话状态
request.session['username'] = username
request.session['uid'] = user.id
return HttpResponse('success')
2)应用.templates.user.xx.html
<form action="/user/reg" method="post">
3)同名目录下.urls.py(主路由): path(‘user/’, include(‘应用.urls’))
from django.urls import path, include
4)应用urls.py
5)修饰器做登陆校验
#first 装饰器 then function
@check_login
def check_login(fn): #first function
def wrap(request, *args, **kwargs): #then parameters
if 'username' not in request.session or 'uid' not in request.session:
c_username = request.COOKIES.get('username')
c_uid = request.COOKIES.get('uid')
if not c_username or not c_uid:
return HttpResponseRedirect('/user/login')
else:
request.session['username'] = c_username
request.session['uid'] = c_uid
return fn(request, *args, **kwargs)
return wrap