Easy file upload handler

 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. Custom FileField with content type and size validation by nemesis 3 years, 6 months ago
  2. Add a "remove file" field for Image- or FileFields by rodrigoc 5 years, 9 months ago
  3. File Mimetype Validator (Using python-magic) by BHSPitMonkey 2 weeks, 1 day ago
  4. Admin Image Widget by baumer1122 5 years, 8 months ago
  5. upload handler decorators by Rozza 5 years, 9 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/

#

(Forgotten your password?)