前言
對於web開來說,用戶登陸、注冊、文件上傳等是最基礎的功能,針對不同的web框架,相關的文章非常多,但搜索之后發現大多都不具有完整性,對於想學習web開發的新手來說不具有很強的操作性;對於web應用來說,包括數據庫的創建,前端頁面的開發,以及中間邏輯層的處理三部分。
本系列以可操作性為主,介紹如何通過django web框架來實現一些簡單的功能。每一章都具有完整性和獨立性。使用新手在動手做的過程中體會web開發的過程,過程中細節請參考相關文檔。
本操作的環境:
===================
deepin linux 2013(基於ubuntu)
python 2.7
Django 1.6.2
===================
創建項目與應用
#創建項目
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/
登陸所需要的用戶名和密碼就是我們第一次同步數據庫時所設置。
然后我們就看到剛剛注冊的那個用戶信息。
本文以實現基本功能為主,當然你可以在此基礎上做更多的事。對用戶注冊信息的驗證,需要再次確認密碼,修改一個漂亮的樣式等。如果有用點個贊吧。