I am trying to upload files and organise the directory structure in the media folder. In specific I want the upload to create subfolders basis one of the values in the model. The issue I face is that in the view I add information to the instance (in my example code this is the relevant profile
). I would like to use this information for the subfolder, but it does not exist in my model until the save which is after the upload...
What would be the appropriate approach to get the information into Upload
so that the subfolder can be created?
Thanks
Model:
class Upload(models.Model):
file = models.FileField(upload_to="upload/")
profile = models.ForeignKey(Profile, blank=True, null=True)
def get_upload_to(self, field_attname):
return 'upload/%d' % self.profile
View:
def profile(request, profile_slug):
profile = Profile.objects.get(slug=profile_slug)
context_dict['profile'] = profile
if request.method=="POST":
for file in request.FILES.getlist('file'):
upload = UploadForm(request.POST, request.FILES)
if upload.is_valid():
newupload = upload.save(commit=False)
newupload.profile = profile
newupload.save()
else:
pass
upload=UploadForm()
context_dict['form'] = upload
return render(request, 'app/profile.html', context_dict)
SOLUTION, thanks to xyres:
Model:
def get_upload_to(instance, filename):
return 'upload/%s/%s' % (instance.profile, filename)
class Upload(models.Model):
file = models.FileField(upload_to=get_upload_to)
profile = models.ForeignKey(Profile, blank=True, null=True)
View:
def profile(request, profile_slug):
profile = Profile.objects.get(slug=profile_slug)
context_dict['profile'] = profile
if request.method=="POST":
upload = UploadForm(request.POST, request.FILES)
if upload.is_valid():
for f in request.FILES.getlist('file'):
Upload.objects.create(file=f, profile=profile)
return redirect(reverse('profile')
else:
pass
return render(request, 'app/profile.html', context_dict)