table of Contents
Django auth module
Command line to create a superuser
python manage.py createsuperuser
Common module auth method
1. Create a user
from django.contrib.auth.models import User
# User.objects.create(username=username,password=password) # 不可用 密码不是加密的
# User.objects.create_user(username=username,password=password) # 创建普通用户 密码自动加密
User.objects.create_superuser(username=username, password=password, email='[email protected]')
2. Verify user login status
from django.contrib import auth
# res = User.objects.filter(username=username,password=password) # 密码无法校验
from django.contrib import auth
# 必须传用户名和密码两个参数缺一不能
user_obj = auth.authenticate(request,username=username,password=password)
3. Save the user login status
auth.login(request, user_obj)
# 只要这句话执行了 后面在任意位置 只要你能拿到request你就可以通过request.user获取到当前登录的用户对象,加了sessionid
4. determine whether the current user login
request.user.is_authenticated()
5. Verify the original password is correct
request.user.check_password(old_password)
6. Change Password
request.user.set_password(new_password)
# 一定要保存
request.user.save()
7. cancellation
auth.logout(request)
8. check whether the user is logged decorator
from django.contrib.auth.decorators import login_required
# 局部配置
@login_required(login_url='/login/')
def logout(request):
auth.logout(request)
return HttpResponse('注销成功')
# 全局配置
# 首先在settings.py文件中直接配置LOGIN_URL = '/login/'
@ login_required
def logout(request):
auth.logout(request)
return HttpResponse('注销成功')
# 如果全局配置了,局部也配置了,那么以局部为准
Extended auth_user Field
method one
One to one relationship between the use of foreign key field
class UserDetail(models.Model):
phone = models.CharField(max_length=32)
user = models.OneToOneField(to='User')
Second way
The use of inheritance
There is a User class in django.contrib.auth.models, which inherits the class AbstractUser
from django.contrib.auth.models import AbstractUser
class Userinfo(AbstractUser):
phone = models.BigIntegerField()
register_time = models.DateField(auto_now_add=True)
Plug-in configuration file-based design
# start.py
import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
if __name__ == '__main__':
os.environ.setdefault('xxx', 'conf.settings')
from lib.conf import settings
print(settings.NAME)
# __init__.py
import importlib
from lib.conf import global_settings
import os
class Settings(object):
def __init__(self):
for name in dir(global_settings):
if name.isupper():
setattr(self, name, getattr(global_settings, name))
module_path = os.environ.get('xxx')
md = importlib.import_module(module_path)
for name in dir(md):
if name.upper():
setattr(self, name, getattr(md, name))
settings = Settings()
csrf_token
When post request will trigger CsrfViewMiddleware middleware
form post request form
Join in the form form {% csrf_token %}
to
In post requests ajax
method one
In writing {% csrf_token%} page
Ajax request is then transmitted at the time of acquiring by the tag lookup random data string to the custom object
data:{'username': username, 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()}
Second way
data:{'username': username, 'csrfmiddlewaretoken': '{{ csrf_token }}'}
File official website provides three ways
New files are copied directly js code can be introduced
csrf related decorator
csrf_exempt
from django.views.decorators.csrf import csrf_exempt
# 不校验csrf
#@csrf_exempt
def index(require):
return HttpResponse('index')
csrf_protect
from django.views.decorators.csrf import csrf_protect
# 只校验加装饰器的方法
#@csrf_protect
def index(require):
return HttpResponse('index')
FBV and CBV difference in csrf decorator
csrf_exempt
csrf_exempt this decorator can only take effect in order to dispatch equipment
@method_decorator(csrf_exempt, name='dispatch')
class MyIndex(views.View):
# @method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get(self, request):
pass
def post(self, request):
pass
csrf_protect
All methods can be csrf_protect