您的位置:首页 > 编程语言 > Go语言

Django form 实现文件上传

2015-08-28 15:32 441 查看

  很久没更新博客了,最近在写项目没时间,做到文件上传的适合,看了虫师的博客觉得不错,就顺便记录一下自己的操作过程:

 models 配置:

class User(models.Model):
    headImg = models.FileField(upload_to = './upload/')
    def __unicode__(self):
        return self.headImg
#####建立一个headImg字段###数据上传到数据库做记录并且在当前项目目录下建立upload文件夹。

  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>
  view 视图文件:
class UserForm(forms.Form):
    headImg = forms.FileField()
def disk(request):
    if request.method == "POST":
        uf = UserForm(request.POST,request.FILES)
        if uf.is_valid():
            headImg = uf.cleaned_data['headImg']
            user = User()
            user.headImg = headImg
            user.save()
            return HttpResponse('upload ok!')
    else:
        uf = UserForm()
    return render_to_response('disk.html',{'uf':uf})
####form方式实现表单显示,并且上传文件。          

上传成功:

mysql查看文件:

mysql> select * from app_user;
+----+-------------------------------+
| id | headImg                       |
+----+-------------------------------+
|  1 | upload/out_W3xCNAW.txt        |
|  2 | upload/out_429apY0.txt        |
|  3 | upload/out.txt                |
|  4 | upload/out_FAvse7g.txt        |
|  5 | upload/新建文本文档.txt       |
|  6 | upload/out_0Cve1aD.txt        |
+----+-------------------------------+

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: