0

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.

Marcus Grass
  • 1,043
  • 2
  • 17
  • 38
  • 1
    Possible duplicate of [Need a minimal Django file upload example](https://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example) – dirkgroten Apr 04 '18 at 20:18
  • @dirkgroten I did see that example, but the problem was that I don't want to save it to a model, but directly to a disk location. – Marcus Grass Apr 04 '18 at 20:42
  • 2
    But that's the basic example of `FileField` in the official [Django documentation](https://docs.djangoproject.com/en/2.0/topics/http/file-uploads/), did you read it? (see `handle_uploaded_file` method!) – dirkgroten Apr 04 '18 at 20:51
  • Seems like [this](https://stackoverflow.com/questions/3702465/how-to-copy-inmemoryuploadedfile-object-to-disk) solves your problem. :) – AEM Jun 06 '23 at 15:19

1 Answers1

1

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)