前言css
對於web開來講,用戶登錄、註冊、文件上傳等是最基礎的功能,針對不一樣的web框架,相關的文章很是多,但搜索以後發現大多都不具備完整性,對於想學習web開發的新手來講不具備很強的操做性;對於web應用來講,包括數據庫的建立,前端頁面的開發,以及中間邏輯層的處理三部分。html
本系列以可操做性爲主,介紹如何經過django web框架來實現一些簡單的功能。每一章都具備完整性和獨立性。但願新手在動手作的過程當中體會web開發的過程,過程當中細節請參考相關文檔。前端
本操做的環境:python
===================linux
deepin linux 2013(基於ubuntu)web
python 2.7數據庫
Django 1.6.2django
===================ubuntu
在上一節中介紹了django 如何實現用戶註冊,用戶註冊好了帳號,就能夠拿着註冊的帳號去登陸了。這一節介紹如何實現用戶登陸。session
建立項目與應用
#建立項目
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 ,跳轉到登陸成功頁面: