Just save the file to a folder in Django

I have a piece of code that gets a file from a form via POST.

file = request.FILES['f'] 

What would be the easiest way to save this file in my media folder in

 settings.MEDIA_ROOT 

I watched this answer , among other things, but I had errors referring to undefined names and invalid chunks methods.

Should there be an easy way to do this?

EDIT Load the method in my views.py:

 def upload(request): folder = request.path.replace("/", "_") uploaded_filename = request.FILES['f'].name # create the folder if it doesn't exist. try: os.mkdir(os.path.join(settings.MEDIA_ROOT, folder)) except: pass # save the uploaded file inside that folder. full_filename = os.path.join(settings.MEDIA_ROOT, folder, uploaded_filename) fout = open(full_filename, 'wb+') file_content = ContentFile( request.FILES['f'].read() ) # Iterate through the chunks. for chunk in file_content.chunks(): fout.write(chunk) fout.close() 
+8
python django django-models django-forms
source share
2 answers

Check out the second part of the answer and remember to import the ContentFile from django.core.files

+5
source share

You can use django FileField , it supports upload_to parameter, for example:

 data_file = models.FileField(upload_to=content_path) 

Where content_path can be a string or a function that returns a string.

+3
source share

All Articles