python⽹页上传⽂件_python+django快速实现⽂件上传
对于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 = (
'ib.admin',
'ib.auth',
'ttypes',
'ib.sessions',
'ssages',
'ib.staticfiles',
'disk',
)
设计Model(数据库)
打开mysite2/disk/models.py⽂件,添加如下内容
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
创建两个字段,username ⽤户存放⽤户名,headImg ⽤户存放上传⽂件的路径。
下⾯进⾏数据库的同步
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 邮箱地址
Password: 密码
Password (again): 确认密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
最后⽣成的 disk_user 表就我是我们models.py 中所创建的类。Django 提供了他们之间的对应关系。创建视图
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、创建注册页⾯
先在mysite2/disk/⽬录下创建templates⽬录,接着在mysite2/disk/templates/⽬录下创建register.html ⽂件:
register
3、设置模板路径
打开mysite2/mysite2/settings.py⽂件,在底部添加:
#template
TEMPLATE_DIRS=(
'/home/fnngj/djpy/mysite2/disk/templates'
)
4、设置URL
f.urls import patterns, include, url
ib import admin
admin.autodiscover()
urlpatterns = patterns('',python新手代码练习
# Examples:
# url(r'^$', 'mysite2.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^disk/', 'ister'),
)
5、启动服务
fnngj@fnngj-H24X:~/djpy/mysite2$ python manage.py runserver
0 errors found
May 20, 2014 - 13:49:21
Django version 1.6.2, using settings 'mysite2.settings'
Quit the server with CONTROL-C.
注册页⾯可以正常打开说明整个过程已经⾛通。这也是Django开发的基本套路。读者⼀定要熟练理解这个基本套路。
完善表单提交
通过上⾯的过程,我们只是把过程串了起来,细⼼你⼀定发现,我们的register.html ⽂件,并没有创建⽤户提交的表单,views.py⽂件中也并没有对⽤户提交的信息做处理。下⾯我们就针对这两个⽂件进⼀步的补充。
打开mysite2/disk/templates/register.html ⽂件:
register
{{uf.as_p}}
打开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):
hod == "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})
填写⽤户名,选择本地上传⽂件,点击“ok”
抛出⼀个错误,这个错误⽐较友好,所以不是我们操作过程中的⼩错误。
打开mysite2/mysite2/settings.py⽂件,将下⾯⼀⾏代码注释:
MIDDLEWARE_CLASSES = (
'ib.sessions.middleware.SessionMiddleware',
'django.middlewaremon.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'ib.auth.middleware.AuthenticationMiddleware',
'ssages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
将数据写⼊数据库
虽然已经实现了数据的提交,但⽤户名与⽂件并没有真正的写⼊到数据库。我们来进⼀步的完善mysite2/disk/views.py ⽂件:#coding=utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse
dels import User
# Create your views here.
class UserForm(forms.Form):
username = forms.CharField()
headImg = forms.FileField()
def register(request):
hod == "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})
那数据库中保存的是什么呢?
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>
通过查看数据库发现,我们数据库中存放的并⾮⽤户上传的⽂件本⾝,⽽是⽂件的存放路径。以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持脚本之家。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。