温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

django用户认证

发布时间:2020-07-02 12:28:23 来源:网络 阅读:734 作者:易金刚 栏目:开发技术

利用django自带认证功能实现用户登录认证。

views.py

# Create your views here.
 
from django.shortcuts import render_to_response,render,get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
from django.contrib.auth.models import User
from django.contrib import auth
 
from forms import LoginForm
 
def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render_to_response('login.html',RequestContext(request,{'form':form,}))
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            user = auth.authenticate(username=username,password=password)
            if user is not None and user.is_active:
                auth.login(request,user)
                return render_to_response('index.html',RequestContext(request))
            else:
                return render_to_response('login.html',RequestContext(request,{'form':form,'password_is_wrong':True}))
        else:
            return render_to_response('login.html',RequestContext(request,{'form':form,}))
 
 
@login_required
def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/login/")
 
 
@login_required
def index(request):
    return render_to_response('index.html')

froms.py

#coding=utf-8
from django import forms
from django.contrib.auth.models import User
 
class LoginForm(forms.Form):
    username = forms.CharField(
            required = True,
            label="用户名",
            error_messages={'required':'请输入用户名'},
            widget=forms.TextInput(
                attrs={
                    'placeholder': "用户名",
                    'class':'form-control'
                    }
                )
            )
 
    password = forms.CharField(
            required=True,
            label="密码",
            error_messages={'required':'请输入密码'},
            widget=forms.PasswordInput(
                attrs={
                    'placeholder':"密码",
                    'class':'form-control'
                    }
                ),
            )
 
    def clean(self):
        if not self.is_valid():
            raise forms.ValidationError("用户名和密码为必填项")
        else:
            cleaned_data = super(LoginForm,self).clean()


login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>登录</title>
<script type="text/javascript" src="/static/bootstrap/js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/static/bootstrap/css/bootstrap-theme.min.css">
<script type="text/javascript" src="/static/bootstrap/js/bootstrap.min.js"></script>
<style type="text/css">
html,body { margin:0; padding:0; overflow:hidden; height:100%; }
#jz-login { margin:0 auto; border:1px solid #666; background-color:#CCC; width:300px; }
</style>
<script type="text/javascript">
function makeItMiddle() {
        document.getElementById('jz-login').style.marginTop = (document.getElementsByTagName('body')[0].offsetHeight - document.getElementById('jz-login').offsetHeight) / 2 + 'px';
}
window.onload = makeItMiddle;
window.onresize = makeItMiddle;
</script>
</head>
<body>
    {% if password_is_wrong %}
<div class="alert alert-error">
        <button type="button" class="close" data-dismiss="alert">×</button>
        <h5>错误!</h5>
        用户名或密码错误
</div>
    {% endif %}
<div class="well" id="jz-login" >
        <h2>用户登录</h2>
        <form class="form-horizontal" action="" method="post">
            {% csrf_token %}
                {{ form }}
                <p>
                </p>
                <p class="form-actions">
                        <input type="submit" value="登录" class="btn btn-primary">
                        <a href="/contactme/"><input type="button" value="忘记密码" class="btn btn-danger"></a>
                        <a href="/contactme/"><input type="button" value="新员工?" class="btn btn-success"></a>
                </p>
        </form>
</div>
<script src="/static/bootstrap/js/jquery.min.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI