django-如何操作models.FileField数据类型

class ModelFormWithFileField(models.Model):
     title = models.CharField(max_length=50)
     file = models.FileField(upload_to='test')
 
     def __unicode__(self):
         return self.title


比如这是我定义的models类

在数据库是这么存的:

+----+-------+-------------------------------------------+
|  id  |  title  |         file                                            |
+----+-------+-------------------------------------------+
|  1 | 123   | data/detail.docx                              |
|  2 | 234   | data/model.txt                                  |
|  3 | 456   | test/10月22PS海报.doc                  |
|  4 | asd   | test/56bfb39bgw1ens2t1aeq.jpg |
|  5 | asd   | test/38.0.2125.24.manifest            |
+----+-------+-------------------------------------------+

进入django环境的shell


这里导入models,并选一个id为3名字为10月22PS海报.doc的对象x,其中x.file即为我们题目里面的models.FileField数据类型

这里出错是因为python2.x的bug,当然python3.x没这个问题,对策如下:


3行代码搞定


import File来包装一下它,包装过的文件会自动close,这是官方的一句话和demo

The following approach may be used to close files automatically:

>>> from django.core.files import File

# Create a Python file object using open() and the with statement
>>> with open('/tmp/hello.world', 'w') as f:
...     myfile = File(f)
...     myfile.write('Hello World')
...
>>> myfile.closed
True
>>> f.closed
True


举例两个属性name和size

当然它的所有属性可以用dir(myFile)来获得:



注意,如果要获得文件的url,不能包装它成为File,只能通过

x.file.url获得


其中的site_media是我在settings.py里面设置的MEDIA_URL


-----------------------------------------------------------------分割线-----------------------------------------------------------------


下面说一下如何获得文件类型来return response

>>> from django.core.servers.basehttp import FileWrapper
>>> import mimetypes
>>> wrapper=FileWrapper(x.file)
>>> content_type=mimetypes.guess_type(x.file.url)
>>> print content_type
('application/msword', None)
>>> x.file.closed
False
>>> myFile.closed
False
>>> x.file.close()
>>> myFile.closed
True

#前提是x.file.url做好映射,让django能找到文件,或者我推测它只是通过后缀来确定


在views.py中:

update_to, filename = str(x.file).split('/')
response=HttpResponse(wrapper,mimetype='content_type')
response['Content-Length'] = x.file.size
response['Content-Disposition']="attachment;filename=%s" % filename
return response

搞定

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值