django 实现文件上传
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django 实现文件上传相关的知识,希望对你有一定的参考价值。
创建项目与应用
django-admin.py startproject mysite cd mysite python manage.py startapp app01
打开mysite/mysite/settings.py文件,将app01应用添加进去:
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, "app01", ]
设计Model(数据库)
打开mysite/app01/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 用户存放上传文件的路径。
下面进行数据库的同步
python manage.py makemigrations python manage.py migrate
最后生成的 app01_user 表就我是我们models.py 中所创建的类。Django 提供了他们之间的对应关系。
创建视图
1、打开mysite/app01/views.py 文件
from django.shortcuts import render,render_to_response # Create your views here. def register(request): return render_to_response(‘register.html‘,{})
2、创建注册页面
先在mysite/app01/目录下创建templates目录,接着在mysite/app01/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、设置模板路径
打开mysite/mysite/settings.py文件,在底部添加:
#template TEMPLATE_DIRS = ( os.path.join(BASE_DIR, ‘templates‘), os.path.join(BASE_DIR, ‘app01/templates‘), )
4、设置URL
from django.conf.urls import url,include from django.contrib import admin from app01 import views as app01 urlpatterns = [ url(r‘^file/‘, app01.register), ]
5、启动服务
python manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEM PLATE_DIRS. System check identified 1 issue (0 silenced). August 31, 2016 - 10:55:12 Django version 1.10, using settings ‘sitename.settings‘ Starting development server at http://0.0.0.0:8000/ Quit the server with CTRL-BREAK.
6、访问http://127.0.0.1:8000/file
完善表单提交
打开mysite/app01/templates/register.html 文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>register</title> </head> <body> <h1>register</h1> <form method="post" enctype="multipart/form-data" > {{uf.as_p}} <input type="submit" value="ok"/> </form> </body> </html>
打开mysite/app01/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})
再次刷新页面
填写用户名,选择本地上传文件,点击“ok”
抛出一个错误,解决方法如下。
打开mysite/mysite/settings.py文件,将下面一行代码注释:
MIDDLEWARE = [ ‘django.middleware.security.SecurityMiddleware‘, ‘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‘, ]
再次刷新网页:
将数据写入数据库
虽然已经实现了数据的提交,但用户名与文件并没有真正的写入到数据库。我们来进一步的完善mysite/app01/views.py 文件:
#coding:utf-8 from django.shortcuts import render,HttpResponse,render_to_response import datetime,os # Create your views here. from django import template from sitename import settings import sys import locale from django import forms from app01.models import User 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})
再次刷新页面,完成文件的上传。
在项目的目录下,我们发现了用户提交的文件。
那数据库中保存的是什么呢?
mysql> select * from app01_user; +----+----------+------------------+ | id | username | headImg | +----+----------+------------------+ | 1 | alex | upload/store.png | | 2 | jwh | upload/store.png | +----+----------+------------------+ 2 rows in set (0.02 sec) mysql>
通过查看数据库发现,我们数据库中存放的并非用户上传的文件本身,而是文件的存放路径。
以上是关于django 实现文件上传的主要内容,如果未能解决你的问题,请参考以下文章