User authentication in Django(用户认证)

一,概述:

auth 系统包括:

1)Users

2)Permissions: Binary (yes/no) flags designating whether a user may perform a certain task.(权限:二进制(是/否)标志,指示用户是否可以执行某个任务。)

3)Groups: A generic way of applying labels and permissions to more than one user.(组:向多个用户应用标签和权限的通用方法。)

4)A configurable password hashing system(一个可配置的密码散列系统)

5)Forms and view tools for logging in users, or restricting content(用于用户登录或者限制内容的表单和视图工具)

6)A pluggable backend system(一个可插入的后台系统)

7)Password strength checking(密码强度检查)

8)Throttling of login attempts(限制登录尝试)

9)Authentication against third-parties (OAuth, for example)(针对第三方的认证,例如(OAuth))

Installation(安装)

1)INSTALLED_APPS中配置 django.contrib.auth' 和django.contrib.contenttypes

2)在MIDDLEWARE中配置 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',

Usage(用法)

一,Using the Django authentication system(使用Django 认证系统)

1)User objects:The primary attributes of the default user are:(默认用户的主要属性): username, password, email,firstname,lastname

2)Creating users:

>>> 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()

3)Creating superusers

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

4)Changing passwords

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

5)Authenticating users

from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
# A backend authenticated the credentials
else:

6)Authentication in Web requests判断用户是否登录

if request.user.is_authenticated:
# Do something for authenticated users.(已登录)
...
else:
# Do something for anonymous users.

7)How to log a user in(如何登录用户)

from django.contrib.auth import authenticate, login

def 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.

8)How to log a user out(如何退出)

from django.contrib.auth import logout

def logout_view(request):
logout(request)
# Redirect to a success page.

8)登录装饰器(The login_required decorator)

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
上一篇:apache 启动不了


下一篇:html 表单input录入内容校验