用户登录的过程就是拿表单信息和数据库中的信息核对,如果正确就记录下用户的Cookies。
定义登录表单类型
class LoginForm(forms.Form): username = forms.CharField(label=‘用户名:‘,max_length=30) password = forms.CharField(label=‘密码:‘,widget=forms.PasswordInput())
判断用户名是否在数据库中
def login_validate(request,username,password): req_value=False user = authenticate(username=username,password=password) if user is not None: if user.is_active: auth_login(request,user) return True return req_value
Views
@csrf_exemptdef login(request): errors = [] if request.method == ‘POST‘: form = LoginForm(request.POST) if form.is_valid(): data = form.cleaned_data username = data[‘username‘] password = data[‘password‘] if login_validate(request,username,password): response = render_to_response(‘index.html‘,{‘username‘:username},RequestContext(request)) response.set_cookie(‘username‘,username,3600) username=request.COOKIES.get(‘username‘,‘‘) return response else: errors.append(‘温馨提示:密码错误,请重新输入!‘) else: errors.append(‘温馨提示:用户名不对,请重新输入!‘) else: form = LoginForm() return render_to_response(‘login.html‘,{‘errors‘:errors,‘form‘:form},RequestContext(request))
时间: 2024-10-10 03:20:33