登录注册功能
配置settings.py
在最后加上
# 配置没有登录则跳转到登录
LOGIN_URL = '/users/login/'
配置templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
M(models):
models.py
V(views):
urls.py
views.py
forms.py
T(templates):
base.html
index.html
login.html
register.html
关联关系:url——>浏览器——>views.py&urls.py——>templates&html——>forms.py&views.py&urls.py——>templates&html
urls.py
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from users import views
urlpatterns = [
# 注册
url(r'^register/', views.register, name='register'),
# 登录
url(r'^login/', views.login, name='login'),
# 首页
url(r'^index/', login_required(views.index), name='index'),
# 注销
url(r'^logout', login_required(views.logout), name='logout'),
]
首先导入相应的库
login_required() 顾名思义,需要登录后才能访问
forms.py
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.Form):
"""
校验注册信息
"""
# username = forms.CharField(required=True)
# password = forms.CharField(required=True)
# password2 = forms.CharField(required=True)
username = forms.CharField(required=True,
max_length=5,
min_length=2,
error_messages={
'required': '用户必填',
'max_length': '长度不能超过5位',
'min_length': '长度不能少于2位'
})
password = forms.CharField(required=True,
min_length=6,
error_messages={
'required': '密码必填',
'min_length': '长度不能少于6位'
})
password2 = forms.CharField(required=True,
min_length=6,
error_messages={
'required': '密码必填',
'min_length': '长度不能少于6位'
})
def clean(self):
# 校验用户名是否已经注册过
user = User.objects.filter(username=self.cleaned_data.get('username'))
if user:
# 已经被注册
raise forms.ValidationError({'username': '用户名已经存在,请直接登录'})
pass
else:
# 没有被注册
pass
# 校验密码和确认密码是否相同
if self.cleaned_data.get('password') != self.cleaned_data.get('password2'):
raise forms.ValidationError({'password2': '两次密码不一致'})
return self.cleaned_data
class CheckUserForm(forms.Form):
username = forms.CharField(required=True,
max_length=5,
min_length=2,
error_messages={
'required': '用户必填',
'max_length': '长度不能超过5位',
'min_length': '长度不能少于2位'
})
password = forms.CharField(required=True,
min_length=6,
error_messages={
'required': '密码必填',
'min_length': '长度不能少于6位'
})
def clean(self):
# 校验用户名是否已经注册过
user = User.objects.filter(username=self.cleaned_data.get('username')).first()
if user:
# 已经被注册
pass
else:
# 没有被注册
raise forms.ValidationError({'username': '用户名不存在!'})
forms.py的作用是检测和过滤从html页面传过来的值,并且返回对应的错误提示。得到期望的数据。
views.py
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from users.forms import UserForm, CheckUserForm
def register(request):
if request.method == 'GET':
return render(request, 'register.html')
if request.method == 'POST':
# 校验页面中传递的参数是否填写完整
# username = request.POST.get('username')
form = UserForm(request.POST)
# is_valid():判断表单是否验证通过
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
User.objects.create_user(username=username, password=password)
# 实现跳转
return HttpResponseRedirect(reverse('users:login'))
else:
return render(request, 'register.html', {'form': form})
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
# 表单验证,用户名和密码是否填写,校验用户名是否注册
form = CheckUserForm(request.POST)
if form.is_valid():
# 校验用户名和密码,判断返回的对象是否为空,如果不为空,则为user对象
user = auth.authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']
)
if user:
# 校验成功 用户名和密码是正确的 加密方法是Django自带的,所以用Django自带的方法
auth.login(request, user)
return HttpResponseRedirect(reverse('users:index'))
else:
# 密码错误
return render(request, 'login.html', {'error': '密码错误'})
else:
return render(request, 'login.html', {'form': form})
def index(request):
if request.method == 'GET':
return render(request, 'index.html')
def logout(request):
if request.method == 'GET':
# 注销
auth.logout(request)
return HttpResponseRedirect(reverse('users:login'))
views.py负责响应请求,根据request中的不同请求完成不同的操作。
知识小结:
forms.py:
- 1.新建UserForm类和CheckUserForm类,并且都继承forms.Form。
- 2.使用forms中的CharField方法对页面中传来的数据进行过滤,并返回错误提示。
- 3.clean方法,对用户信息进行查重。
views.py:
- 1.实例化UserForm和CheckUserForm,调用is_valid()方法判断表单是否验证通过,通过为True,不通过为False且返回错误报告(return render(request, 'register.html', {'form': form}))
- 2.auth.authenticate()校验用户名和密码,判断返回的对象是否为空,如果不为空,则为user对象
user = auth.authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']
)
- 3.auth.login(request, user) 用户登入
校验成功,用户名和密码是正确的则允许登入。request中user有匿名用户(AnonymousUser)变为指定用户。 加密方法是Django自带的,所以用Django自带的方法 - 4.auth.logout(request) 注销
将request中的user用户变为匿名用户(AnonymousUser),实现登出。