用户注册功能
model
假如有下面的 model
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
pass
# 这里是继承了 Django 的 model
视图函数
配合验证码中的视图继续编写用户注册逻辑
from django.shortcuts import render
from django.contrib.auth.hashers import make_password
from users.models import UserProfile
def some_view(request):
if request.POST:
registerform = CaptchaTestForm(request.POST)
# check the input
if form.is_valid():
user_name = register_form.cleaned_data.get(
'email')
password = register_form.cleaned_data.get(
'password')
# 给用户的密码加密
password = make_password(password)
UserProfile.objects.create(
**{"username": user_name,
"email": user_name,
"password": password})
return render(request, 'login.html')
else:
form = CaptchaTestForm()
return render(request, 'register.html',locals())
登录验证
==前提条件是使用 Django
自带的 User
model, 或者自定义的 model,但是这个 model 需要继承 AbstractUser
==
1. 基于 FBV
# 验证用户
from django.contrib.auth import authenticate
# 验证成功后,把用户放进 session 中
from django.contrib.auth import login
# 用户退出则删除 session
from django.contrib.auth import logout
模板语言可以在前端判断用户是否通过了验证,返回 True/False
{% if request.user.is_authenticated %}
Examp
users.views.py
登录
def user_login(request):
if request.method == "POST":
user_name = request.POST.get('username')
password = request.POST.get('password')
user_obj = authenticate(username=user_name,
password=password)
if user_obj:
login(request, user_obj)
return render(request, 'index.html')
else:
return render(request, 'login.html',
{"msg": "用户名或密码错误"})
elif request.method == "GET":
return render(request, 'login.html')
退出登录
users.views.py
def user_logout(request):
logout(request)
return redirect('/')
添加自定义验证功能
users.views.py
如下示例是验证用户名或者邮箱
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from users.models import UserProfile
class CustomBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
# 通过用户名或邮箱来获取用户对象
user_obj = UserProfile.objects.get(
Q(username=username) | Q(email=username)
)
# 验证用户的密码
if user.check_password(password):
return user_obj
except Exception as e:
return None
视图函数原来的代码不变
在 settings.py
文件中配置如下内容
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackend', # 注意后面的逗号
)
网友评论