前面说了,用户注册,今天我们就来说说用户登录吧。今天说的是使用Django的session功能,而不是它的auth模块,后期,如果有机会的话,我再写点auth认证登录。


其实重点就是request.session功能,默认Django就将其session功能打开了,我们仅仅需要的是配置下数据库。


website/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'tc',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT':'' ,

    }
}


登录表单(用户登录认证的活,我放在表单里喽):

mysite/forms.py

class LoginForm(forms.Form):
    username = forms.CharField(error_messages={'required':'请输入用户名'})
    password = forms.CharField(widget=forms.PasswordInput,error_messages={'required':'请输入密码'})

    def clean(self):
        cleaned_data=super(LoginForm,self).clean()
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        if username and password:
            try:
                member=Register.objects.get(username__exact=username)
            except Register.DoesNotExist:
                self._errors['username'] = self.error_class([u"用户不存在"])
                return
            if member.password != password:
                self._errors['password'] = self.error_class([u"密码不一致"])
        return cleaned_data


登录与登出

mysite/views.py

def login(request):
    login_user = request.session.get('username',"")
    if login_user:
        return render(request,"login.html",{'username':login_user})
        
    if request.method == 'POST':
        loginform = LoginForm(request.POST,error_class=DivErrorList)
        if loginform.is_valid():
            request.session['username']=loginform.cleaned_data['username']
            return render(request,"login.html",{'username':request.session['username']})
    else:
        loginform = LoginForm()
    return render(request,"login.html",{'loginform':loginform})


def logout(request):
    login_user = request.session.get('username',"")
    if login_user:
        del request.session['username']
    else:
        loginform = LoginForm()
        return render(request,"login.html",{'loginform':loginform})
    return HttpResponse("登出成功!登录")

模板:

mysite/templates/login.html

{% extends "base.html" %}

{% block title %}
用户登录
{% endblock %}

{% block content %}

{% if not username %}


{% csrf_token %}
用户登录

用户名:` loginform`.`username `{{ loginform.username.errors|safe}}

密码:` loginform`.`password `{{ loginform.password.errors|safe}}



{% else %}
欢迎管理员:`username`,登出
{% endif %}
{% endblock %}


导向

website/urls.py

    url(r'^login/','mysite.views.login'),
    url(r'^logout/','mysite.views.logout'),
    url(r'^success/(?P\w+)/$','mysite.views.success'),


有了这些,我们便可以实现用户登录了,并且做了相应的检验,就这么简单...


如果想了解更多,请关注我们的公众号
公众号ID:opdevos
扫码关注

Django学习之用户登录_第1张图片