I had the opportunity to get the file path of an uploaded file using Django’s ModelForm, so I am making a note of it.
Assume the following model.
class Document(models.Model):
file = models.FileField(upload_to='documents/')
With the above, the path could be accessed using the following views.
from django.shortcuts import render, redirect
from .forms import DocumentForm
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
document = form.save()
file_url = document.file.url # Correct field name used here
full_path = document.file.path # Correct field name used here
return redirect('some-view')
else:
form = DocumentForm()
return render(request, 'upload.html', {'form': form})
This may be basic, but I hope you find it helpful.