网络编程
位置:首页>> 网络编程>> Python编程>> python+django快速实现文件上传

python+django快速实现文件上传

作者:虫师  发布时间:2021-03-12 19:07:38 

标签:django,python,文件上传

对于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

目录结构如下:

python+django快速实现文件上传

打开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(数据库)                                                                         

打开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.com  邮箱地址
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 文件:


<?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、设置模板路径

打开mysite2/mysite2/settings.py文件,在底部添加:


#template
TEMPLATE_DIRS=(
'/home/fnngj/djpy/mysite2/disk/templates'
)

4、设置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、启动服务


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/

python+django快速实现文件上传

注册页面可以正常打开说明整个过程已经走通。这也是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/ 页面

python+django快速实现文件上传

填写用户名,选择本地上传文件,点击“ok”

python+django快速实现文件上传

抛出一个错误,这个错误比较友好,所以不是我们操作过程中的小错误。

 打开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/ 页面,我们就可以正常将用户名和文件提交了!

python+django快速实现文件上传

将数据写入数据库         

虽然已经实现了数据的提交,但用户名与文件并没有真正的写入到数据库。我们来进一步的完善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/ 页面,完成文件的上传。

python+django快速实现文件上传

那数据库中保存的是什么呢?


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>

通过查看数据库发现,我们数据库中存放的并非用户上传的文件本身,而是文件的存放路径。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com