對於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 mysite2
fnngj@fnngj-H24X:~/djpy$ cd mysite2
#在專案下建立一個disk應用程式
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py startapp disk
開啟mysite2/mysite2/settings.py文件,將disk應用程式加入:
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'disk', )
設計Model(資料庫)
from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length = 30) headImg = models.FileField(upload_to = './upload/') def __unicode__(self): return self.username
fnngj@fnngj-H24X:~/djpy/mysite2$ 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 disk_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)
創建視圖
1.開啟mysite2/disk/views.py 檔案
from django.shortcuts import render,render_to_response # Create your views here. def register(request): return render_to_response('register.html',{})
先在mysite2/disk/目錄下建立templates目錄,接著在mysite2/disk/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> <body> <h1>register</h1> </body> </html>
開啟mysite2/mysite2/settings.py文件,在底部新增:
#template TEMPLATE_DIRS=( '/home/fnngj/djpy/mysite2/disk/templates' )
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite2.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^disk/', 'disk.views.register'), )
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py runserver Validating models... 0 errors found May 20, 2014 - 13:49:21 Django version 1.6.2, using settings 'mysite2.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
註冊頁面可以正常開啟說明整個過程已經走通。這也是Django開發的基本套路。讀者一定要熟練理解這個基本套路。
完善表单提交
通过上面的过程,我们只是把过程串了起来,细心你一定发现,我们的register.html 文件,并没有创建用户提交的表单,views.py文件中也并没有对用户提交的信息做处理。下面我们就针对这两个文件进一步的补充。
打开mysite2/disk/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> <body> <h1>register</h1> <form method="post" enctype="multipart/form-data" > {{uf.as_p}} <input type="submit" value="ok"/> </form> </body> </html>
打开mysite2/disk/views.py 文件:
from django.shortcuts import render,render_to_response from django import forms from django.http import HttpResponse # Create your views here. class UserForm(forms.Form): username = forms.CharField() headImg = forms.FileField() def register(request): if request.method == "POST": uf = UserForm(request.POST,request.FILES) if uf.is_valid(): return HttpResponse('upload ok!') else: uf = UserForm() return render_to_response('register.html',{'uf':uf})
再次刷新http://127.0.0.1:8000/disk/ 页面
填写用户名,选择本地上传文件,点击“ok”
抛出一个错误,这个错误比较友好,所以不是我们操作过程中的小错误。
打开mysite2/mysite2/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', )
再次刷新http://127.0.0.1:8000/disk/ 页面,我们就可以正常将用户名和文件提交了!
将数据写入数据库
虽然已经实现了数据的提交,但用户名与文件并没有真正的写入到数据库。我们来进一步的完善mysite2/disk/views.py 文件:
#coding=utf-8 from django.shortcuts import render,render_to_response from django import forms from django.http import HttpResponse from disk.models import User # Create your views here. class UserForm(forms.Form): username = forms.CharField() headImg = forms.FileField() def register(request): if request.method == "POST": uf = UserForm(request.POST,request.FILES) if uf.is_valid(): #获取表单信息 username = uf.cleaned_data['username'] headImg = uf.cleaned_data['headImg'] #写入数据库 user = User() user.username = username user.headImg = headImg user.save() return HttpResponse('upload ok!') else: uf = UserForm() return render_to_response('register.html',{'uf':uf})
再次刷新http://127.0.0.1:8000/disk/ 页面,完成文件的上传。
那数据库中保存的是什么呢?
fnngj@fnngj-H24X:~/djpy/mysite2$ sqlite3 db.sqlite3 SQLite version 3.7.15.2 2013-01-09 11:53:05 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> select * from disk_user; 1 | Alen | upload/desk.jpg sqlite>
通过查看数据库发现,我们数据库中存放的并非用户上传的文件本身,而是文件的存放路径。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。