如何判断身份验证
在视图层中,
如果没有经过身份验证,request.user将被设置成 django.contrib.auth.models.AnonymousUser的实例,request.auth 将被设置成None。
如果经过身份验证,request.user将被设置为django.contrib.auth.models.User的实例
创建用户
>>> from django.contrib.auth.models import User>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
def create_user(self, username, email=None, password=None, **extra_fields):extra_fields.setdefault('is_staff', False)extra_fields.setdefault('is_superuser', False)return self._create_user(username, email, password, **extra_fields)
更新用户信息
>>> user = User.objects.last()>>> user.last_name = 'Lennon'>>> user.save()
创建超级用户
python manage.py createsuperuser --username=joe --email=joe@example.com
更改密码
>>> from django.contrib.auth.models import User>>> u = User.objects.get(username='john')>>> u.set_password('new password')>>> u.save()
验证用户
from django.contrib.auth import authenticateuser = authenticate(username='john', password='secret')if user is not None:# A backend authenticated the credentialselse:# No backend authenticated the credentials
def authenticate(request=None, **credentials):for backend, backend_path in _get_backends(return_tuples=True):try:user = backend.authenticate(request, **credentials)except PermissionDenied:breakuser.backend = backend_pathreturn user
会话维持
调用login()方法后,会在 session 中保存用户的ID。
from django.contrib.auth import authenticate, logindef my_view(request):username = request.POST['username']password = request.POST['password']user = authenticate(request, username=username, password=password)if user is not None:login(request, user)# Redirect to a success page....else:# Return an 'invalid login' error message....
def login(request, user, backend=None):...request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)request.session[BACKEND_SESSION_KEY] = backendrequest.session[HASH_SESSION_KEY] = session_auth_hash
限制对未登录用户的访问
1)原始方式
from django.conf import settingsfrom django.shortcuts import redirectdef my_view(request):if not request.user.is_authenticated:return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
或者显示一个错误信息:
from django.shortcuts import renderdef my_view(request):if not request.user.is_authenticated:return render(request, 'myapp/login_error.html')# ...
2)使用装饰器
from django.contrib.auth.decorators import login_required@login_requireddef my_view(request):...
3)使用基于类的视图
from django.contrib.auth.mixins import LoginRequiredMixinclass MyView(LoginRequiredMixin, View):login_url = '/login/'redirect_field_name = 'redirect_to'
相关文档
https://docs.djangoproject.com/zh-hans/3.2/topics/auth/default/
