Simple Django Image Upload - Image file not saving

前端 未结 3 1192
说谎
说谎 2021-02-11 05:42

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_RO

3条回答
  •  暖寄归人
    2021-02-11 06:30

    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()
    

提交回复
热议问题