P52基本实现
session在浏览器上查看,F12
session在服务器端查看,数据库django_session
# Form和ModelForm两种方式对比
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(
label="用户名",
widget=forms.TextInput(attrs={'class': 'form-control'}),
required=True,
)
password = forms.CharField(
label="密码",
widget=forms.PasswordInput(
attrs={'class': 'form-control'},
render_value=True,
),
required=True,
)
# 在attr中向前端添加class样式,也可以多继承
def clean_password(self):
pwd = self.cleaned_data.get("password")
from app03_phone_number_management.utils.encrypt import md5
return md5(pwd)
class LoginModelForm(forms.ModelForm):
class Meta:
models = models.Admin
fields = ['username', 'password']
def login(request):
if request.method == 'GET':
form = LoginForm()
return render(request, 'login.html', {'form': form})
# else:
form = LoginForm(data=request.POST)
if form.is_valid():
# test
# print(form.cleaned_data)
# return HttpResponse('提交成功')
# 验证校验:
# admin_object = models.Admin.objects.filter(username=form.cleaned_data['username'], password=form.cleaned_data['password']).first()
# 定义类时的字段名要和数据库中的一致
admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
if not admin_object:
form.add_error("password", "用户名或密码错误")
return render(request, 'login.html', {'form': form})
# else用户名正确:
request.session['info'] = {
'id': admin_object.id,
'name': admin_object.username,
}
return redirect('/admin_list/')
# else:
return render(request, 'login.html', {'form': form})
P53中间件处理
可以将视图函数检验是否登录封装成一个装饰器函数(比较麻烦,每个都要@)
也可以利用中间件:
请求进来要经过中间件到视图函数
响应到客户端也要经过中间件才能到客户端