前言css
對於web開來講,用戶登錄、註冊、文件上傳等是最基礎的功能,針對不一樣的web框架,相關的文章很是多,但搜索以後發現大多都不具備完整性,對於想學習web開發的新手來講不具備很強的操做性;對於web應用來講,包括數據庫的建立,前端頁面的開發,以及中間邏輯層的處理三部分。html
本系列以可操做性爲主,介紹如何經過django web框架來實現一些簡單的功能。每一章都具備完整性和獨立性。使用新手在動手作的過程當中體會web開發的過程,過程當中細節請參考相關文檔。前端
本操做的環境:python
===================linux
deepin linux 2013(基於ubuntu)web
python 2.7數據庫
Django 1.6.2django
===================ubuntu
建立項目與應用 session
#建立項目
fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite3
fnngj@fnngj-H24X:~/djpy$ cd mysite3
#在項目下建立一個account應用
fnngj@fnngj-H24X:~/djpy/mysite3$ python manage.py startapp account
目錄結構以下:
打開mysite3/mysite3/settings.py文件,將應用添加進去:
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', )
設計Model(數據庫)
打開mysite3/account/models.py文件,添加以下內容
from django.db import models # Create your models here.
class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.EmailField()
按照慣例先建立數據庫,建立三個字段,用戶存放用戶名、密碼、email 地址等。
下面進行數據庫的同步
fnngj@fnngj-H24X:~/djpy/mysite3$ 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 account_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)
最後生成的 account_user 表就是咱們models.py 中所建立的User類。Django 提供了他們之間的對應關係。
建立視圖(邏輯層)
打開mysite3/account/views.py 文件:
#coding=utf-8
from django.shortcuts import render from django import forms from django.shortcuts import render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from account.models import User #定義表單模型
class UserForm(forms.Form): username = forms.CharField(label='用戶名:',max_length=100) passworld = forms.CharField(label='密碼:',widget=forms.PasswordInput()) email = forms.EmailField(label='電子郵件:') # Create your views here.
def register(request): if request.method == "POST": uf = UserForm(request.POST) if uf.is_valid(): #獲取表單信息
username = uf.cleaned_data['username'] passworld = uf.cleaned_data['passworld'] email = uf.cleaned_data['email'] #將表單寫入數據庫
user = User() user.username = username user.passworld = passworld user.email = email user.save() #返回註冊成功頁面
return render_to_response('success.html',{'username':username}) else: uf = UserForm() return render_to_response('register.html',{'uf':uf})
的這個邏輯中主要作了幾件事,首先提供給用戶一個註冊頁面(register.html),UserForm類定義了表單在註冊頁面上的顯示。接受用戶填寫的表單信息,而後將表單信息寫入到數據庫,最後返回給用戶一個註冊成功的頁面(success.html)
建立模板文件(前端頁面)
在邏輯層提到了兩個頁面,一個註冊頁,一個註冊成功頁面。因此咱們要把這兩個頁面建立出來。
先在mysite3/account/目錄下建立templates目錄,接着在mysite3/account/templates/目錄下建立register.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>
mysite3/account/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>
設置模板路徑
打開mysite3/mysite3/settings.py文件,在底部添加:
#template
TEMPLATE_DIRS=( '/home/fnngj/djpy/mysite3/account/templates' )
設置URL
設置URL的配置也是django web框架的一大特點。打開mysite3/mysite3/urls.py:
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples:
# url(r'^$', 'mysite3.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)), url(r'^account/', include('account.urls')), )
在mysite3/account/目錄下建立urls.py文件:
from django.conf.urls import patterns, url from account import views urlpatterns = patterns('', url(r'^$', views.register, name='register'), url(r'^register/$',views.register,name = 'register'), )
這裏人配置表示:訪問
http://127.0.0.1:8000/account/
http://127.0.0.1:8000/account/register/
都會指向一個註冊頁面。
體驗註冊
當全部工做都完成以後,下面體驗一下咱們的註冊功能吧。
啓動服務:
fnngj@fnngj-H24X:~/djpy/mysite3$ python manage.py runserver
Validating models...
0 errors found
May 21, 2014 - 14:31:32
Django version 1.6.2, using settings 'mysite3.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
訪問註冊頁面:
由於在register.html 文件中加了一點樣式,因此看上去好看了一點,但做爲一個審美的人觀念的人沒法容忍這樣醜陋的頁面存在。
以避免錯誤的再次出現,
打開mysite3/mysite3/settings.py文件,將下面一行代碼註釋:
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', )
如今能夠做爲一個用戶去填寫表單了。
註冊的用戶哪兒去了?
你依然能夠像昨天同樣去查詢數據庫,但爲何不利用admin呢?
打開mysite3/account/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) email = models.EmailField() class UserAdmin(admin.ModelAdmin): list_display = ('username','email') admin.site.register(User,UserAdmin)
從新初始化數據庫:
fnngj@fnngj-H24X:~/djpy/mysite3$ python manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
登錄admin 後臺
http://127.0.0.1:8000/admin/
登錄所須要的用戶名和密碼就是咱們第一次同步數據庫時所設置。
而後咱們就看到剛剛註冊的那個用戶信息。
本文以實現基本功能爲主,固然你能夠在此基礎上作更多的事。對用戶註冊信息的驗證,須要再次確認密碼,修改一個漂亮的樣式等。若是有用點個贊吧。