Django學習之用戶登陸

前面說了,用戶註冊,今天咱們就來講說用戶登陸吧。今天說的是使用Django的session功能,而不是它的auth模塊,後期,若是有機會的話,我再寫點auth認證登陸。html


其實重點就是request.session功能,默認Django就將其session功能打開了,咱們僅僅須要的是配置下數據庫。mysql


website/settings.pyweb

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

    }
}sql


登陸表單(用戶登陸認證的活,我放在表單裏嘍):數據庫

mysite/forms.pydjango

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_datasession


登陸與登出
ide

mysite/views.pyui

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})url


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("登出成功!<a href='/login/'>登陸</a>")

模板:

mysite/templates/login.html

{% extends "base.html" %}

{% block title %}
用戶登陸
{% endblock %}

{% block content %}

{% if not username %}

<form action="/login/" method="POST">
{% csrf_token %}
用戶登陸</br>
用戶名:` loginform`.`username `{{ loginform.username.errors|safe}}</br>
密碼:` loginform`.`password `{{ loginform.password.errors|safe}}</br>
<input type="submit" value="登陸"/>
</form>
{% else %}
歡迎管理員:`username`,<a href="/logout/">登出</a>
{% endif %}
{% endblock %}


導向

website/urls.py

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


有了這些,咱們即可以實現用戶登陸了,而且作了相應的檢驗,就這麼簡單...


若是想了解更多,請關注咱們的公衆號
公衆號ID:opdevos
掃碼關注

gongzhouhao.jpg

相關文章
相關標籤/搜索