I think this is what you want, assuming getname
is entered into the form in your view:
First, your model:
def upload_function(instance, filename):
getname = instance.name
# Add other filename logic here
return customfilename # Return the end filename where you want it saved.
class Document(models.Model):
name = models.CharField(max_length=25)
docfile = models.FileField(upload_to=upload_function) # The upload_to argument sends it to your upload function.
In this case, you're creating your own upload_to
function (here called upload_function
). You can read about that here. When running this function, it will pass the instance as a first argument, so you can access its properties. Thus, we'll access its name
when creating our filename. Further explanation here.
Now your view:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import DocumentForm
from .models import Document
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
instance = Document(docfile=request.FILES['file'])
instance.save()
return HttpResponseRedirect('/success/url/')
else:
form = DocumentForm()
return render(request, 'upload.html', {'form': form})
This view checks your form to make sure it's valid, then saves the uploaded file. Assuming your DocumentForm
has a field for name
, this will be assigned first, which means your function for upload_to
will be able to access it. The sample language for this view came from the Django docs here.
Please let me know if this works.