File Uploads are covered in the Django Documentation.
There are slight differences depending on if you're trying to upload a file to a Model
that got a FileField
or ImageField
, or if you just simply want to upload a file to your server that does not belong to any model using the Form
class.
Please notice, Django have a Form
class (Docs) that help you generate forms and handle the POST
request with validation and so on. Use this class instead of writing your own HTML code.
Upload File Without Model (Docs)
# forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
# views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
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(request, 'upload.html', {'form': form})
Upload File With Model (Docs)
# views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ModelFormWithFileField
def upload_file(request):
if request.method == 'POST':
form = ModelFormWithFileField(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = ModelFormWithFileField()
return render(request, 'upload.html', {'form': form})
media/
folder ? or you just need to save it tomedia/
folder without pushing to database ?