一、实现文件上传
1定义模型
#上传作品表:作品名称,用户名 class Upload(models.Model): #注意这里的用户名是FileField类型 name = models.FileField(upload_to = './upload/') username = models.CharField(max_length = 20) def __str__(self): return self.name
2定义模版
<form method="post" enctype="multipart/form-data" > {{uf.as_p}} <input type="submit" value="上传"/> </form>
3定义视图
def user(request): print "user" if request.method == "POST": uf = UploadFileForm(request.POST,request.FILES) if uf.is_valid(): #获取表单信息 #username = uf.cleaned_data['username'] headImg = uf.cleaned_data['headImg'] print str(headImg) #写入数据库 upload = Upload() upload.name = headImg upload.username = request.user.username upload.save() return HttpResponse('upload ok!') else: return HttpResponse("表单验证失败") else: uf = UploadFileForm() return render_to_response('user.html',{'uf':uf , "user":request.user})
4配置url
url(r'^user/$' , 'account.views.user'),
这样就实现了文件上传功能
二、展示上传的文件
(例如图片等)
根据django官方文档的说明:https://docs.djangoproject.com/en/1.7/topics/files/#using-files-in-models
我们定义的模型中一个字段name是文件字段,但是其实存储的是上传的图片或文件的路径
name = models.FileField(upload_to = './upload/')
我们需要配置upload上传路径
1在settings.py中添加
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload') MEDIA_URL = '/upload/'
2在url中配置路径:
达成的效果是: 让 MEDIA_URL 等同于 MEDIAA_ROOT
from django.conf import settings from django.conf.urls.static import static urlpatterns = patterns('', # Examples: url(r'^admin/', include(admin.site.urls)), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
注意:在 patterns(....)后面加上 static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
3在模板中设置图片或文件路径
<body> {% if upload %} <!--在你的字段中获取url属性进行展示--> <img src="{{upload.name.url}}" /> {% endif %} </body>
关键在于: 比如你从后台获取查询的数据叫做upload , upload.name是FileField的字段,只需要获取其url属性进行展示即可