Marcus Grass
Marcus Grass

Reputation: 1083

Django simplest way to save file to folder on disk without using a model

I'm trying to save a file from an upload directly to my folder media/files, exactly as described in this thread.

Here my form code:

from django import forms

class UploadForm(forms.Form):
    title=forms.CharField(max_length=50)
    file=forms.FileField()

Here's my view code:

def uploadview(request):
    if request.method == 'POST':
        form=UploadForm(request.POST, request.FILES)
        if form.is_valid() and request.FILES['file']:
            uploaded_filename=request.FILES['file'].name
            full_filename=os.path.join('media', 'files', uploaded_filename)
            fout=open(full_filename, 'wb+')
            file_content=ContentFile(request.FILES['file'].read())
            for chunk in file_content.chunks():
                fout.write(chunk)
            fout.close()
            return HttpResponseRedirect('/App/')
    else:
        form=UploadForm()

    return render(request, 'App/uploads.html', {'form':form})

I get no errors, just a redirect to the /App/ page and no file has been downloaded. My goal here is no be able to just get a file done on disk like you can do in PHP with this simple command.

move_uploaded_file(($_FILES["filetoupload"]["tmp_name"]), $target_file)

Upvotes: 1

Views: 4986

Answers (1)

A. Rose
A. Rose

Reputation: 468

Remember to set the enctype in the form, like:

enctype="multipart/form-data"

That's usually what I've forgotten if I try to upload a file and don't see it, but don't get any errors.

There's a good reference for file upload in django here:

https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html

Upvotes: 2

Related Questions