python+django快速實(shí)現(xiàn)文件上傳
對(duì)于web開來說,用戶登陸、注冊(cè)、文件上傳等是最基礎(chǔ)的功能,針對(duì)不同的web框架,相關(guān)的文章非常多,但搜索之后發(fā)現(xiàn)大多都不具有完整性,對(duì)于想學(xué)習(xí)web開發(fā)的新手來說就沒辦法一步一步的操作練習(xí);對(duì)于web應(yīng)用來說,包括數(shù)據(jù)庫的創(chuàng)建,前端頁面的開發(fā),以及中間邏輯層的處理三部分。
本系列以可操作性為主,介紹如何通過django web框架來實(shí)現(xiàn)一些簡(jiǎn)單的功能。每一章都具有完整性和獨(dú)立性。使用新手在動(dòng)手做的過程中體會(huì)web開發(fā)的過程,過程中細(xì)節(jié)請(qǐng)參考相關(guān)文檔。
本操作的環(huán)境:
===================
deepin linux 2013(基于ubuntu)
python 2.7
Django 1.6.2
===================
創(chuàng)建項(xiàng)目與應(yīng)用
#創(chuàng)建項(xiàng)目
fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite2
fnngj@fnngj-H24X:~/djpy$ cd mysite2
#在項(xiàng)目下創(chuàng)建一個(gè)disk應(yīng)用
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py startapp disk
目錄結(jié)構(gòu)如下:
打開mysite2/mysite2/settings.py文件,將disk應(yīng)用添加進(jìn)去:
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'disk', )
設(shè)計(jì)Model(數(shù)據(jù)庫)
打開mysite2/disk/models.py文件,添加如下內(nèi)容
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
創(chuàng)建兩個(gè)字段,username 用戶存放用戶名,headImg 用戶存放上傳文件的路徑。
下面進(jìn)行數(shù)據(jù)庫的同步
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'): 用戶名(默認(rèn)當(dāng)前系統(tǒng)用戶名) Email address: fnngj@126.com 郵箱地址 Password: 密碼 Password (again): 確認(rèn)密碼 Superuser created successfully. Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s)
最后生成的 disk_user 表就我是我們models.py 中所創(chuàng)建的類。Django 提供了他們之間的對(duì)應(yīng)關(guān)系。
創(chuàng)建視圖
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',{})
2、創(chuàng)建注冊(cè)頁面
先在mysite2/disk/目錄下創(chuàng)建templates目錄,接著在mysite2/disk/templates/目錄下創(chuàng)建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>
3、設(shè)置模板路徑
打開mysite2/mysite2/settings.py文件,在底部添加:
#template TEMPLATE_DIRS=( '/home/fnngj/djpy/mysite2/disk/templates' )
4、設(shè)置URL
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'), )
5、啟動(dòng)服務(wù)
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.
6、訪問http://127.0.0.1:8000/disk/
注冊(cè)頁面可以正常打開說明整個(gè)過程已經(jīng)走通。這也是Django開發(fā)的基本套路。讀者一定要熟練理解這個(gè)基本套路。
完善表單提交
通過上面的過程,我們只是把過程串了起來,細(xì)心你一定發(fā)現(xiàn),我們的register.html 文件,并沒有創(chuàng)建用戶提交的表單,views.py文件中也并沒有對(duì)用戶提交的信息做處理。下面我們就針對(duì)這兩個(gè)文件進(jìn)一步的補(bǔ)充。
打開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/ 頁面
填寫用戶名,選擇本地上傳文件,點(diǎn)擊“ok”
拋出一個(gè)錯(cuò)誤,這個(gè)錯(cuò)誤比較友好,所以不是我們操作過程中的小錯(cuò)誤。
打開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/ 頁面,我們就可以正常將用戶名和文件提交了!
將數(shù)據(jù)寫入數(shù)據(jù)庫
雖然已經(jīng)實(shí)現(xiàn)了數(shù)據(jù)的提交,但用戶名與文件并沒有真正的寫入到數(shù)據(jù)庫。我們來進(jìn)一步的完善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'] #寫入數(shù)據(jù)庫 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/ 頁面,完成文件的上傳。
那數(shù)據(jù)庫中保存的是什么呢?
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>
通過查看數(shù)據(jù)庫發(fā)現(xiàn),我們數(shù)據(jù)庫中存放的并非用戶上傳的文件本身,而是文件的存放路徑。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Django實(shí)現(xiàn)文件上傳下載功能
- GO語言實(shí)現(xiàn)文件上傳代碼分享
- Python+django實(shí)現(xiàn)文件上傳
- Django實(shí)現(xiàn)文件上傳和下載功能
- Python+django實(shí)現(xiàn)簡(jiǎn)單的文件上傳
- golang語言實(shí)現(xiàn)的文件上傳與文件下載功能示例
- Django處理文件上傳File Uploads的實(shí)例
- Django框架文件上傳與自定義圖片上傳路徑、上傳文件名操作分析
- Python的Django中將文件上傳至七牛云存儲(chǔ)的代碼分享
- Go語言實(shí)現(xiàn)文件上傳
相關(guān)文章
利用pyuic5將ui文件轉(zhuǎn)換為py文件的方法
今天小編就為大家分享一篇利用pyuic5將ui文件轉(zhuǎn)換為py文件的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python for Informatics 第11章之正則表達(dá)式(二)
這篇文章主要介紹了Python for Informatics 第11章 正則表達(dá)式(二)的相關(guān)資料,需要的朋友可以參考下2016-04-04基于Python實(shí)現(xiàn)全自動(dòng)二維碼識(shí)別
這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)全自動(dòng)二維碼識(shí)別功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11keras訓(xùn)練曲線,混淆矩陣,CNN層輸出可視化實(shí)例
這篇文章主要介紹了keras訓(xùn)練曲線,混淆矩陣,CNN層輸出可視化實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06使用python將多個(gè)excel文件合并到同一個(gè)文件的方法
這篇文章主要介紹了使用python將多個(gè)excel文件合并到同一個(gè)文件的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07使用Python對(duì)Excel進(jìn)行讀寫操作
學(xué)習(xí)Python的過程中,我們會(huì)遇到Excel的讀寫問題。這時(shí),我們可以使用xlwt模塊將數(shù)據(jù)寫入Excel表格中,使用xlrd模塊從Excel中讀取數(shù)據(jù)。下面我們介紹如何實(shí)現(xiàn)使用Python對(duì)Excel進(jìn)行讀寫操作。2017-03-03Tensorflow 1.0之后模型文件、權(quán)重?cái)?shù)值的讀取方式
今天小編就為大家分享一篇Tensorflow 1.0之后模型文件、權(quán)重?cái)?shù)值的讀取方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02