Marcus Grass
Marcus Grass

Reputation: 1083

Django save uploaded file to disk

I'm trying to save a file to disk, not in a class or anything just straight to disk but I can't for the life of me figure out how.

So far I've got:

View: `

def uploadview(request):
    uploadtestvar='Uploadpage!'
    request.session['test']='Is this working?'
    if request.method == 'POST':
        form=UploadForm(request.POST, request.FILES)
        if form.is_valid():
            forcetitle='test'
            try:
                pass
            except:
                pass
            return HttpResponseRedirect('/test/')
    else:
        form=UploadForm()

    return render(request, 'test/uploads.html',{'uploadtestvar':uploadtestvar, 'form':form})`

Form stolen directly from Django:

from django import forms

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

I've searched countless threads and found none that gives an example simple enough for me to understand how to get that request.FILES['file'] saved to disk somewhere. The possible filetypes are png, jpg, and pdf.

Upvotes: 1

Views: 2114

Answers (1)

Wendinoda Washaya
Wendinoda Washaya

Reputation: 35

Pass FileSystemStorage to FileField in models where FileSystemStorage has the storage directory

from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location = 'media/files/')

class UploadModel(models.Model):
    title=forms.CharField(max_length = 50)
    file=forms.FileField(storage = fs)

Upvotes: 1

Related Questions