登錄注冊功能
配置settings.py
在最后加上
# 配置沒有登錄則跳轉(zhuǎn)到登錄
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
關(guān)聯(lián)關(guān)系: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):
# 校驗用戶名是否已經(jīng)注冊過
user = User.objects.filter(username=self.cleaned_data.get('username'))
if user:
# 已經(jīng)被注冊
raise forms.ValidationError({'username': '用戶名已經(jīng)存在使碾,請直接登錄'})
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):
# 校驗用戶名是否已經(jīng)注冊過
user = User.objects.filter(username=self.cleaned_data.get('username')).first()
if user:
# 已經(jīng)被注冊
pass
else:
# 沒有被注冊
raise forms.ValidationError({'username': '用戶名不存在趴俘!'})
forms.py的作用是檢測和過濾從html頁面?zhèn)鬟^來的值,并且返回對應的錯誤提示除抛。得到期望的數(shù)據(jù)。
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':
# 校驗頁面中傳遞的參數(shù)是否填寫完整
# 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)
# 實現(xiàn)跳轉(zhuǎn)
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負責響應請求盈魁,根據(jù)request中的不同請求完成不同的操作彭沼。
知識小結(jié):
forms.py:
- 1.新建UserForm類和CheckUserForm類,并且都繼承forms.Form备埃。
- 2.使用forms中的CharField方法對頁面中傳來的數(shù)據(jù)進行過濾,并返回錯誤提示姓惑。
- 3.clean方法,對用戶信息進行查重按脚。
views.py:
- 1.實例化UserForm和CheckUserForm,調(diào)用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)變?yōu)橹付ㄓ脩簟?加密方法是Django自帶的堪遂,所以用Django自帶的方法 - 4.auth.logout(request) 注銷
將request中的user用戶變?yōu)槟涿脩?AnonymousUser)介蛉,實現(xiàn)登出。