如何判断身份验证

在视图层中,

如果没有经过身份验证,request.user将被设置成 django.contrib.auth.models.AnonymousUser的实例,request.auth 将被设置成None

如果经过身份验证,request.user将被设置为django.contrib.auth.models.User的实例

创建用户

  1. >>> from django.contrib.auth.models import User
  2. >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
  1. def create_user(self, username, email=None, password=None, **extra_fields):
  2. extra_fields.setdefault('is_staff', False)
  3. extra_fields.setdefault('is_superuser', False)
  4. return self._create_user(username, email, password, **extra_fields)

更新用户信息

  1. >>> user = User.objects.last()
  2. >>> user.last_name = 'Lennon'
  3. >>> user.save()

创建超级用户

  1. python manage.py createsuperuser --username=joe --email=joe@example.com

更改密码

  1. >>> from django.contrib.auth.models import User
  2. >>> u = User.objects.get(username='john')
  3. >>> u.set_password('new password')
  4. >>> u.save()

验证用户

  1. from django.contrib.auth import authenticate
  2. user = authenticate(username='john', password='secret')
  3. if user is not None:
  4. # A backend authenticated the credentials
  5. else:
  6. # No backend authenticated the credentials
  1. def authenticate(request=None, **credentials):
  2. for backend, backend_path in _get_backends(return_tuples=True):
  3. try:
  4. user = backend.authenticate(request, **credentials)
  5. except PermissionDenied:
  6. break
  7. user.backend = backend_path
  8. return user

会话维持

调用login()方法后,会在 session 中保存用户的ID。

  1. from django.contrib.auth import authenticate, login
  2. def my_view(request):
  3. username = request.POST['username']
  4. password = request.POST['password']
  5. user = authenticate(request, username=username, password=password)
  6. if user is not None:
  7. login(request, user)
  8. # Redirect to a success page.
  9. ...
  10. else:
  11. # Return an 'invalid login' error message.
  12. ...
  1. def login(request, user, backend=None):
  2. ...
  3. request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
  4. request.session[BACKEND_SESSION_KEY] = backend
  5. request.session[HASH_SESSION_KEY] = session_auth_hash

限制对未登录用户的访问

1)原始方式

  1. from django.conf import settings
  2. from django.shortcuts import redirect
  3. def my_view(request):
  4. if not request.user.is_authenticated:
  5. return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

或者显示一个错误信息:

  1. from django.shortcuts import render
  2. def my_view(request):
  3. if not request.user.is_authenticated:
  4. return render(request, 'myapp/login_error.html')
  5. # ...

2)使用装饰器

  1. from django.contrib.auth.decorators import login_required
  2. @login_required
  3. def my_view(request):
  4. ...

3)使用基于类的视图

  1. from django.contrib.auth.mixins import LoginRequiredMixin
  2. class MyView(LoginRequiredMixin, View):
  3. login_url = '/login/'
  4. redirect_field_name = 'redirect_to'

相关文档

https://docs.djangoproject.com/zh-hans/3.2/topics/auth/default/