前言
对于web开来说,用户登陆、注册、文件上传等是最基础的功能,针对不同的web框架,相关的文章非常多,但搜索之后发现大多都不具有完整性,对于想学习web开发的新手来说不具有很强的操作性;对于web应用来说,包括数据库的创建,前端页面的开发,以及中间逻辑层的处理三部分。
本系列以可操作性为主,介绍如何通过django web框架来实现一些简单的功能。每一章都具有完整性和独立性。希望新手在动手做的过程中体会web开发的过程,过程中细节请参考相关文档。
本操作的环境:
===================
deepin linux 2013(基于ubuntu)
python 2.7
Django 1.6.2
===================
在上一节中介绍了django 如何实现用户注册,用户注册好了账号,就可以拿着注册的账号去登录了。这一节介绍如何实现用户登录。
创建项目与应用
#创建项目
fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite4
fnngj@fnngj-H24X:~/djpy$ cd mysite4
#在项目下创建一个login应用
fnngj@fnngj-H24X:~/djpy/mysite4$ python manage.py startapp login
项目目录结构如下:
打开mysite4/mysite4/settings.py文件,将应用添加进去:
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'login',
)
……
#顺便注释csrf
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
设计model(数据库)
打开mysite4/login/models.py文件,添加如下内容
from django.db import models
from django.contrib import admin
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
admin.site.register(User)
创建一个User表,有两个字段username、password
然后,进行数据库的同步:
fnngj@fnngj-H24X:~/djpy/mysite4$ python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table login_user
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes 输入yes/no
Username (leave blank to use 'fnngj'): 用户名(默认当前系统用户名)
Email address: fnngj@126.com 邮箱地址
Password: 密码
Password (again): 确认密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
配置URL
打开mysite4/mysite4/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite5.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
启动服务
fnngj@fnngj-H24X:~/djpy/mysite4$ python manage.py runserver
Validating models...
0 errors found
May 21, 2014 - 14:31:32
Django version 1.6.2, using settings 'mysite4.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
访问admin
登录用户名和密码为我们进行数据库同步时所设置的信息。
登录之后,选择add 添加用户。
创建用户,点击save
再次打开mysite4/login/models.py文件,添加如下内容
from django.db import models
from django.contrib import admin
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
class UserAdmin(admin.ModelAdmin):
list_display = ('username','password')
admin.site.register(User,UserAdmin)
再次刷新,admin后台,如下显示:
创建视图
现在我们已经生成了一个用户信息表,下面要做的就是设计用户登录功能了。
打开mysite4/login/views.py 文件
#coding=utf-8
from django.shortcuts import render,render_to_response
from django.http import HttpResponseRedirect
from login.models import User
from django import forms
#定义表单模型
class UserForm(forms.Form):
username = forms.CharField(label='用户名:',max_length=100)
password = forms.CharField(label='密码:',widget=forms.PasswordInput())
#登录
def login(request):
if request.method == 'POST':
uf = UserForm(request.POST)
if uf.is_valid():
#获取表单用户密码
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
#获取的表单数据与数据库进行比较
user = User.objects.filter(username__exact = username,password__exact = password)
if user:
return render_to_response('success.html',{'username':username})
else:
return HttpResponseRedirect('/login/')
else:
uf = UserForm()
return render_to_response('login.html',{'uf':uf})
上面登录的核心是比较,拿到用户填写的表单数据(用户名、密码)与数据库User表中的字段进行比较,根据比较结果,如果成功跳转到success.html页面,如果失败还留在原来页面login.html 。
创建模板
根据视图层的要求,我们需要创建两个页面,success.html 和login.html
先在mysite4/login/目录下创建templates目录,接着在mysite4/login/templates/目录下创建login.html 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>登录</title>
</head>
<style type="text/css">
body{color:#efd;background:#453;padding:0 5em;margin:0}
h1{padding:2em 1em;background:#675}
h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
p{margin:1em 0}
</style>
<body>
<h1>登录页面:</h1>
<form method = 'post' enctype="multipart/form-data">
{{uf.as_p}}
<input type="submit" value = "ok" />
</form>
</body>
</html>
在mysite4/login/templates/目录下创建success.html 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<h1>恭喜{{username}},登录成功!</h1>
</form>
</body>
</html>
设置模板路径
打开mysite4/mysite4/settings.py文件,在底部添加:
#template
TEMPLATE_DIRS=(
'/home/fnngj/djpy/mysite4/login/templates'
)
配置URL
打开mysite4/mysite4/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite5.views.home', name='home'),
url(r'^login/', include('login.urls')),
url(r'^admin/', include(admin.site.urls)),
)
创建文件mysite4/login/urls.py
from django.conf.urls import patterns, url
from login import views
urlpatterns = patterns('',
url(r'^$', views.login, name='login'),
)
启动服务(python manage.py runserver),
访问登录页面(http://127.0.0.1:8000/login/)
用户名、密码正确,点击OK ,跳转到登录成功页面: