Django Example: FileField and ImageField

The syntax to add it in Model is:

class MyModel(models.Model):
	video = FileField(upload_to=None[, max_length=100, **options])

Here upload_to is local filesystem path that will be appended to your MEDIA_ROOT setting to determine the value of the url( attribute.

Setting MEDIA_ROOT and upload_to

MEDIA_ROOT = ‘/home/myname/files/
file: abc.flv
results in: /home/myname/files/videos/abc.flv

where as if,
MEDIA_ROOT = ‘/home/myname/files/’
and file : abc.flv
result will be saved in : ‘/videos/abc.flv’ (i.e., root directory of filesystem)

You can also set upload_to=’videos/%Y/%m/%d’. The ‘%Y/%m/%d’ part of upload_to is strftime formatting; ‘%Y’ is the four-digit year, ‘%m’ is the two-digit month and ‘%d’ is the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in the directory /home/myname/files/videos/2007/01/15.

Now here’s how would you save the actual data.

from django.core.files.base import ContentFile
def save_file(request):
	mymodel = MyModel.objects.get(id=1)
	file_content = ContentFile(request.FILES['video'].read())['video'].name, file_content)

Hope the code is self explanatory. For further help do drop comment.

8 Responses

  1. chris #

    How do you resolve problem with 1 user adding a big video file, and second one want to visit your site.

    My prolem is that when I’m uploading a file, the rest of the system is down, and none can use it.

  2. Fenris #

    Is the explicit set of the file necessary? I think that if you have a MyModelForm and do
    model = MyModelForm(request.POST, request.FILES) thats all you need

  3. Michal #

    Exist some way, how to resolve this with chunks instead of read ?

  4. Django中实用imageField实现图片上传 | 岭南六少 - 一朵在LAMP架构下挣扎的云 #

    […] 参考: 分类: Django, Python 标签: Django (还没有人评分)  Loading … Python 程序员的进化Python多线程下载文件Python与Ruby一些有用的Python函式庫列表Django子域的实现用Python实现CRUD功能REST服务python web.py使用flup lighttpd优化过程浅谈Python web框架linux上部署Django项目(Apache+mod_wsgi+django)网站架构总结 评论 (0) Trackbacks (0) 发表评论 Trackback […]

  5. 使用django的ImageField和forms from models快速制作上传图片表单 #

    […] 上面的方法不一定是最好的,不过也提供了一些思路。另外,即便是不使用forms from models,也可以方便的使用ImageField保存图片:见 […]


Leave a Reply