今天来实现用户登录模块

首先,我们创建一个表单(forms.py):

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

该表单有两个域username和password,这两个域都为必填项。

接着,我们定义login的视图(view.py):

from django.shortcuts import render_to_response,render,get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib import messages
from django.template.context import RequestContext from django.forms.formsets import formset_factory
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from bootstrap_toolkit.widgets import BootstrapUneditableInput
from django.contrib.auth.decorators import login_required 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,}))

该视图实例化了之前定义的LoginForm,它的主要业务逻辑是:

1. 判断必填项用户名和密码是否为空,如果为空,提示"用户名和密码为必填项”的错误信息

2. 判断用户名和密码是否正确,如果错误,提示“用户名或密码错误"的错误信息

3. 登陆成功后,进入主页

login.html定义如下:

<!DOCTYPE html>
{% load bootstrap_toolkit %}
{% load url from future %}
<html lang="en">
<head>
<meta charset="utf-8">
<title>数据库脚本发布系统</title>
<meta name="description" content="">
<meta name="author" content="朱显杰">
{% bootstrap_stylesheet_tag %}
{% bootstrap_stylesheet_tag "responsive" %}
<style type="text/css">
body {
padding-top: 60px;
}
</style>
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
{% bootstrap_javascript_tag %}
{% block extra_head %}{% endblock %}
</head> <body> {% if password_is_wrong %}
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>错误!</h4>用户名或密码错误
</div>
{% endif %}
<div class="well">
<h1>数据库脚本发布系统</h1>
<p> </p>
<form class="form-horizontal" action="" method="post">
{% csrf_token %}
{{ form|as_bootstrap:"horizontal" }}
<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> </body>
</html>

最后还需要在urls.py里添加:

    (r'^accounts/login/$',  'dbrelease_app.views.login'),

最终的效果如下:

1)当在浏览器里输入http://192.168.1.16:8000/accounts/login/,出现如下登陆界面:

2)当用户名或密码为空时,提示”用户名和密码为必填项",如下所示:

3)当用户名或密码错误时,提示“用户名或密码错误",如下所示:

4)如果用户名和密码都正确,进入主页。

有login,自然会有logout,logout的视图定义如下:

@login_required
def logout(request):
auth.logout(request)
return HttpResponseRedirect("/accounts/login/")

urls.py里添加:

(r'^accounts/logout/$', 'dbrelease_app.views.logout'),

[Django实战] 第4篇 - 用户认证(用户登录)的更多相关文章

  1. [Django实战] 第3篇 - 用户认证(初始配置)

    当大家打开一个网站时,第一步做什么?大部分一定是先登录吧,所以我们就从用户认证开始. 打开用户认证 Django本身已经提供了用户认证模块,使用它可以大大简化用户认证模块的开发,默认情况下,用户认证模 ...

  2. [Django实战] 第5篇 - 用户认证(修改密码)

    上一篇我们实现了用户认证系统的登录模块,这一篇实现修改密码模块. 同样地,我们首先得给修改密码创建表单(forms.py): class ChangepwdForm(forms.Form): oldp ...

  3. django用户认证系统——登录4

    用户已经能够在我们的网站注册了,注册就是为了登录,接下来我们为用户提供登录功能.和注册不同的是,Django 已经为我们写好了登录功能的全部代码,我们不必像之前处理注册流程那样费劲了.只需几分钟的简单 ...

  4. [Django实战] 第8篇 - 分页列表

    当用户登录成功后,首先看到的是他自己之前提交的任务列表,本篇将实现该页面. 视图(views.py)里定义如下: from django.core.paginator import Paginator ...

  5. [Django实战] 第9篇 - 表单、视图、模型、模板的交互

    本章通过实现一个用户提交任务请求的页面,讲述表单.视图.模型.模板间的交互. 首先,我们需要定义一个表单(forms.py) class CreatetaskForm(forms.Form): cre ...

  6. 5、Django实战第5天:首页和登录页面的配置

    从这天开始我们需要用到前端源码,需要的朋友可以进行小额打赏(15元),打赏二维码在博客的右侧,打赏后可以凭截图联系463951510@qq.com,博主收到邮件后会立即回复发送所有源码素材,实战过程中 ...

  7. Django——用户认证

    Django--用户认证 用户与Authentication(身份验证) Django 用户认证系统处理用户帐号,组,权限以及基于cookie的用户会话. 这个系统一般被称为 auth/auth (认 ...

  8. Tornado web.authenticated 用户认证浅析

    在Web服务中会有用户登录后的一系列操作, 如果一个客户端的http请求要求是用户登录后才能做得操作, 那么 Web服务器接收请求时需要判断该请求里带的数据是否有用户认证的信息. 使用Tornado框 ...

  9. MySQL用户认证及权限grant-revoke

    一.MySQL用户认证: 登录并不属于访问控制机制,而属于用户身份识别和认证: 1.用户名-user 2.密码-password 3.登录mysqld主机-host 实现用户登录MySQL,建立连接. ...

随机推荐

  1. Android 使用SpannableString显示复合文本

    http://blog.csdn.net/feizhixuan46789/article/details/10334441 http://www.th7.cn/Program/Android/2014 ...

  2. ORACLE客户端乱码

    sqlplus 打开CMD窗口,出现乱码情况的解决办法 C:\Documents and Settings>set NLS_LANG=american_america.AL32UTF8 C:\D ...

  3. SQL Server截取字符串和处理中文技巧

    一 环境介绍 SQL  Server PRINT @@VERSION MicrosoftSQLServer2012-11.0.2100.60(X64) Feb10201219:39:15 Copyri ...

  4. Codeforces Round #270 A~D

    Codeforces Round #270 A. Design Tutorial: Learn from Math time limit per test 1 second memory limit ...

  5. db2常用命令(详解)大全

    近一年来在项目开发中使用到了IBM的DB2 9.1的数据库产品,跟Oracle相比一些命令有很大的区别,而它最大的功能是支持      xml存储.检索机制,通过XPath进行解析操作,使开发人员免于 ...

  6. wcf 出现 IsContentTypeSupported 错误

    查看添加的服务地址是不是https开头的,而 *.config 文件里面自动添加的链接变成了http,当前的bindbing类型为basicHttpBinding, 解决方法:在config文件里面手 ...

  7. How to Create Dump File for Applications

    使用WinDBG这个工具,可以在应用程序异常终止或者无响应时获取它的尸体,以用来解剖研究. Creating Dump File      在Vista环境中抓取Dump文件很方便,在task man ...

  8. TImage也有OnClick事件,可以当按钮使用,配上合适的图片(背景透明,效果前凸)更是几乎以假乱真

    本质上TImage与TSpeedButton没有什么区别,都是没有句柄的,但都可以执行OnClick事件.有空分析一下.

  9. 基于visual Studio2013解决C语言竞赛题之1026判断排序

          题目 解决代码及点评 /********************************************************************** ...

  10. hdu3999The order of a Tree (二叉平衡树(AVL))

    Problem Description As we know,the shape of a binary search tree is greatly related to the order of ...