django用户认证

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

views.py

 1 # Create your views here.
 2  
 3 from django.shortcuts import render_to_response,render,get_object_or_404
 4 from django.http import HttpResponse, HttpResponseRedirect
 5 from django.contrib.auth.decorators import login_required
 6 from django.template.context import RequestContext
 7 from django.contrib.auth.models import User
 8 from django.contrib import auth
 9  
10 from forms import LoginForm
11  
12 def login(request):
13     if request.method == 'GET':
14         form = LoginForm()
15         return render_to_response('login.html',RequestContext(request,{'form':form,}))
16     else:
17         form = LoginForm(request.POST)
18         if form.is_valid():
19             username = request.POST.get('username','')
20             password = request.POST.get('password','')
21             user = auth.authenticate(username=username,password=password)
22             if user is not None and user.is_active:
23                 auth.login(request,user)
24                 return render_to_response('index.html',RequestContext(request))
25             else:
26                 return render_to_response('login.html',RequestContext(request,{'form':form,'password_is_wrong':True}))
27         else:
28             return render_to_response('login.html',RequestContext(request,{'form':form,}))
29  
30  
31 @login_required
32 def logout(request):
33     auth.logout(request)
34     return HttpResponseRedirect("/login/")
35  
36  
37 @login_required
38 def index(request):
39     return render_to_response('index.html')

froms.py

 1 #coding=utf-8
 2 from django import forms
 3 from django.contrib.auth.models import User
 4  
 5 class LoginForm(forms.Form):
 6     username = forms.CharField(
 7             required = True,
 8             label="用户名",
 9             error_messages={'required':'请输入用户名'},
10             widget=forms.TextInput(
11                 attrs={
12                     'placeholder': "用户名",
13                     'class':'form-control'
14                     }
15                 )
16             )
17  
18     password = forms.CharField(
19             required=True,
20             label="密码",
21             error_messages={'required':'请输入密码'},
22             widget=forms.PasswordInput(
23                 attrs={
24                     'placeholder':"密码",
25                     'class':'form-control'
26                     }
27                 ),
28             )
29  
30     def clean(self):
31         if not self.is_valid():
32             raise forms.ValidationError("用户名和密码为必填项")
33         else:
34             cleaned_data = super(LoginForm,self).clean()

login.html

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5 <title>登录</title>
 6 <script type="text/javascript" src="/static/bootstrap/js/jquery.min.js"></script>
 7 <link rel="stylesheet" type="text/css" href="/static/bootstrap/css/bootstrap.min.css">
 8 <link rel="stylesheet" type="text/css" href="/static/bootstrap/css/bootstrap-theme.min.css">
 9 <script type="text/javascript" src="/static/bootstrap/js/bootstrap.min.js"></script>
10 <style type="text/css">
11 html,body { margin:0; padding:0; overflow:hidden; height:100%; }
12 #jz-login { margin:0 auto; border:1px solid #666;  300px; }
13 </style>
14 <script type="text/javascript">
15 function makeItMiddle() {
16         document.getElementById('jz-login').style.marginTop = (document.getElementsByTagName('body')[0].offsetHeight - document.getElementById('jz-login').offsetHeight) / 2 + 'px';
17 }
18 window.onload = makeItMiddle;
19 window.onresize = makeItMiddle;
20 </script>
21 </head>
22 <body>
23     {% if password_is_wrong %}
24 <div class="alert alert-error">
25         <button type="button" class="close" data-dismiss="alert">×</button>
26         <h4>错误!</h4>
27         用户名或密码错误
28 </div>
29     {% endif %}
30 <div class="well" id="jz-login" style="margin:auto">
31         <h1>用户登录</h1>
32         <form class="form-horizontal" action="" method="post">
33             {% csrf_token %}
34                 {{ form }}
35                 <p>
36                 </p>
37                 <p class="form-actions">
38                         <input type="submit" value="登录" class="btn btn-primary">
39                         <a href="/contactme/"><input type="button" value="忘记密码" class="btn btn-danger"></a>
40                         <a href="/contactme/"><input type="button" value="新员工?" class="btn btn-success"></a>
41                 </p>
42         </form>
43 </div>
44 <script src="/static/bootstrap/js/jquery.min.js"></script>
45 <script src="/static/bootstrap/js/bootstrap.min.js"></script>
46 </body>
47 </html>
原文地址:https://www.cnblogs.com/xtbao/p/6257353.html