Login

Easy file upload handler

Author:
mattdw
Posted:
September 7, 2008
Language:
Python
Version:
1.0
Score:
8 (after 8 ratings)

This function emulates the file upload behaviour of django's admin, but can be used in any view. It takes a list of POST keys that represent uploaded files, and saves the files into a date-formatted directory in the same manner as a FileField's upload_to argument.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#
# settings.py
#

# I use this in the 'upload_to' arg for FileFields
# and ImageFields, hence making it a setting.
UPLOAD_PATH = 'uploads/%Y/%m'


#
# this can go wherever (mine is just at the top of my views.py)
#

from django.conf import settings

from datetime import date
import os

def handle_uploads(request, keys):
    saved = []
    
    upload_dir = date.today().strftime(settings.UPLOAD_PATH)
    upload_full_path = os.path.join(settings.MEDIA_ROOT, upload_dir)

    if not os.path.exists(upload_full_path):
        os.makedirs(upload_full_path)

    for key in keys:
        if key in request.FILES:
            upload = request.FILES[key]
            while os.path.exists(os.path.join(upload_full_path, upload.name)):
                upload.name = '_' + upload.name
            dest = open(os.path.join(upload_full_path, upload.name), 'wb')
            for chunk in upload.chunks():
                dest.write(chunk)
            dest.close()
            saved.append((key, os.path.join(upload_dir, upload.name)))
    # returns [(key1, path1), (key2, path2), ...]
    return saved


#
# example usage in a view
#

def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            my_instance = MyModel()
            ...

            saved_images = handle_uploads(request, ['thumbnail_image', 'banner_image'])
            for image in saved_images:
                setattr(my_instance, image[0], image[1])

            my_instance.save()

            ...

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

penguin (on March 7, 2011):

Where can I see this code in action?

#

julian_baker (on November 23, 2013):

How to quickly upload files in Ajax with Django in 5 steps

https://waaave.com/tutorial/django/how-to-quickly-upload-files-in-ajax-with-django-in-5-steps/

#

Please login first before commenting.