Django点滴(三)---用户认证
http://cdpsecurecdp.docs.djangoproject.com/en/dev/topics/auth/default/
启用中间件和模块在settings.py中, MIDDLEWARE_CLASSES启用SessionMiddleware 和AuthenticationMiddleware ;同时,INSTALLED_APPS启用'django.contrib.auth' 和'django.contrib.contenttypes' 。>>> from django.contrib.auth.models import User>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')# At this point, user is a User object that has already been saved# to the database. You can continue to change its attributes# if you want to change other fields.>>> user.last_name = 'Lennon'>>> user.save()
>>> u = User.objects.get(username__exact='john')>>> u.set_password('new password')>>> u.save()
from django.contrib.auth import authenticateuser = authenticate(username='john', password='secret')if user is not None: # the password verified for the user if user.is_active: print("User is valid, active and authenticated") else: print("The password is valid, but the account has been disabled!")else: # the authentication system was unable to verify the username and password print("The username and password were incorrect.")
myuser.groups = [group_list]myuser.groups.add(group, group, ...)myuser.groups.remove(group, group, ...)myuser.groups.clear()myuser.user_permissions = [permission_list]myuser.user_permissions.add(permission, permission, ...)myuser.user_permissions.remove(permission, permission, ...)myuser.user_permissions.clear()
from django.contrib.auth.models import Group, Permissionfrom django.contrib.contenttypes.models import ContentTypecontent_type = ContentType.objects.get(app_label='myapp', model='BlogPost')permission = Permission.objects.create(codename='can_publish', name='Can Publish Posts', content_type=content_type)判断用户是否拥有某个权限
from django.contrib.auth import logoutdef logout_view(request): logout(request) # Redirect to a success page.限制未登录用户。
from django.shortcuts import redirectdef my_view(request): if not request.user.is_authenticated(): return redirect('/login/?next=%s' % request.path) # ...
强制要求验证,使用注解。可以指定要跳转的登陆URL,并在url.py中适当配置。
from django.contrib.auth.decorators import login_required@login_required(login_url='/accounts/login/')def my_view(request): user = request.user还可以对登录要求一些规则验证或者权限验证,不符合就跳回登录URL。
from django.contrib.auth.decorators import user_passes_testdef email_check(user): return '@example.com' in user.email@user_passes_test(email_check, login_url='/login/')def my_view(request): ...
from django.contrib.auth.decorators import permission_required@permission_required('polls.can_vote', login_url='/loginpage/')def my_view(request): ...
{% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p>{% else %} <p>Welcome, new user. Please log in.</p>{% endif %}
{% if perms.foo %} <p>You have permission to do something in the foo app.</p> {% if perms.foo.can_vote %} <p>You can vote!</p> {% endif %} {% if perms.foo.can_drive %} <p>You can drive!</p> {% endif %}{% else %} <p>You don't have permission to do anything in the foo app.</p>{% endif %}