码迷,mamicode.com
首页 > Web开发 > 详细

django实现快速文件上传

时间:2016-02-10 23:23:49      阅读:538      评论:0      收藏:0      [点我收藏+]

标签:

摘自http://www.cnblogs.com/fnng/p/3740274.html

数据库

from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length = 30)
    headImg = models.FileField(upload_to = ‘test/‘)  #注意是路径是跟在MEDIA_ROOT下

    def __unicode__(self):
        return self.username

模板

<?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>

视图

#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})

  

csrf设置:setting.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‘,
)

  

技术分享技术分享

 

django实现快速文件上传

标签:

原文地址:http://www.cnblogs.com/songbird/p/5186199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!