Search code examples
djangofile-uploaddjango-formsdjango-uploads

Simple Django Image Upload - Image file not saving


Right I'm learning how to do a simple image upload form to upload an image to MEDIA_ROOT. The form renders fine, I get no errors, but the file is not showing up in the MEDIA_ROOT directory. If followed the documentation example and can't get it to work and I know it is because I have not understood django file upload handeling properly. So here is my code:

forms.py

from django import forms

class UploadImageForm(forms.Form):
    image = forms.ImageField()

views.py

def merchant_image_upload(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            FileUploadHandler(request.FILES['image'])
            return HttpResponseRedirect('/dashboard/gallery')
    else:
        form = UploadImageForm()
    return render_to_response('gallery.html', RequestContext(request, {'form': form}))

template file

{% extends 'base.html' %}
{% block main %}
    <form action="{% url scvd.views.merchant_image_upload %}" method="post">{% csrf_token %}
        {{ form.image }}
        <input type="submit" value="Upload" />
    </form>
{% endblock %}

Hopefully that's sufficient info to get some help. Please let me know what else I can provide. Thank you, I really appreciate the help.


Solution

  • You don't need to attach it to a model as Matt S states, request.FILES has all the data for the image if your form is set up correctly.

    You need to make sure use enctype="multipart/form-data" in your element, as the docs state here: https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files-to-a-form

    Aside from that, read the docs about file uploads: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

    All you need is well documented there. Hope this helps!

    EDIT OP requested more information on File Uploads

    From the docs:

    Most of the time, you'll simply pass the file data from request into the form as described in Binding uploaded files to a form. This would look something like:

    from django.http import HttpResponseRedirect
    from django.shortcuts import render_to_response
    
    # Imaginary function to handle an uploaded file.
    from somewhere import handle_uploaded_file
    
    def upload_file(request):
        if request.method == 'POST':
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                handle_uploaded_file(request.FILES['file'])
                return HttpResponseRedirect('/success/url/')
        else:
            form = UploadFileForm()
        return render_to_response('upload.html', {'form': form})
    

    And they have an example of how you could write the handle_uploaded_file function:

    def handle_uploaded_file(f):
        destination = open('some/file/name.txt', 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()