Django用户认证功能

Django提供了比较方便的用户认证模块,只要导入它,就可以很方便就完成用户认证。

用户认证

主流有两种写法,一个是直接写成函数,一个写成类,重载get和post方法

  1. 用函数实现
    <path-to-your-app>/views.py
    主要的函数就两个authenticate()login()
    一个是认证登录,一个是保存登录信息。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    from django.contrib.auth import authenticate, login

    def login_view(request):
    if request.method == 'POST':
    user_name = request.POST.get('username', '')
    pass_word = request.POST.get('password', '')
    user = authenticate(request, username=user_name, password=pass_word)
    if user is not None:
    login(request, user)
    return render(request, 'index.html')
    else:
    return render(request, 'login.html', {"msg": "用户或密码错误"})
    if request.method == 'GET':
    return render(request, 'login.html')

然后在urls.py

1
2
3
4
5
6
7
8
9
from users.views import login_view

urlpatterns = [
url(r'^xadmin/', xadmin.site.urls),
url(r'^form/$', get_form),
url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),
url(r'^login/$', login_view),
]

  1. 用类重载get,post方法实现(推荐)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class LoginView(View):
    def get(self, request):
    return render(request, 'login.html')

    def post(self, request):
    user_name = request.POST.get('username', '')
    pass_word = request.POST.get('password', '')
    user = authenticate(request, username=user_name, password=pass_word)
    if user is not None:
    login(request, user)
    return render(request, 'index.html')
    else:
    return render(request, 'login.html', {"msg": "用户或密码错误"})
    urls.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from users.views import LoginView

    urlpatterns = [
    url(r'^xadmin/', xadmin.site.urls),
    url(r'^form/$', get_form),
    url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),
    # url(r'^login/$', login_view),
    url(r'^login/$', LoginView.as_view()),
    ]

    用户名或邮箱

    如果需要用户用邮箱也能登录,则重载authenticate方法就行了。
    首先定义和重载authenticate方法,调用用户模型,利用Q对象组合查询条件,实现等条件查询。这里用|,或组合查询。
    确定存在这个账户后,调用check_password对比密码,如果符合,就返回用户信息。
    <path-to-your-app>/views.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    from django.contrib.auth.backends import ModelBackend
    from django.db.models import Q

    from .models import UserProfile

    # Create your views here.


    class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
    try:
    user = UserProfile.objects.get(Q(username=username) | Q(email=username))
    if user.check_password(password):
    return user
    except Exception as e:
    return None

    然后将上面的类注册到settings.py
    1
    2
    3
    AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
    )

done.

关注公众号 尹安灿