I have the following model that includes a file upload by a user.
def resume_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/resume/<filename>
return 'user_{0}/resume/{1}'.format(instance.student_user.id, filename)
class Resume(models.Model):
resume = models.FileField(upload_to=resume_path, blank=True, null=True)
pub_date = models.DateTimeField(default=timezone.now)
student_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
Then, I would like to allow a user to select one of their uploaded files in a later form. So, I need to be able to dynamically set the path to the directory containing that user's files similar to the dynamic way that I set the upload_path in the original model.
I've tried the following according to this link:
def resume_directory_path(instance):
# returns the path: MEDIA_ROOT/user_<id>/resume/
return 'user_{0}/resume/'.format(instance.student_user.id)
class JobApplication(models.Model):
student_user = models.ForeignKey(StudentUser, on_delete = models.CASCADE)
resume = models.FilePathField(path=resume_directory_path, null=True)
However, looking at the documentation for FilePathField in Django 3.0, it doesn't look like it takes a callable for the path attribute. So, I'm not sure how the answer in the above link answers my question. What is the best way to achieve this functionality?
I'd like to do something like the below:
class CallableFilePathField(models.FilePathField):
def __init__(self, *args, **kwargs):
kwargs['path'] = resume_directory_path(instance)
super().__init__(*args, **kwargs)
class JobApplication(models.Model):
student_user = models.ForeignKey(StudentUser, on_delete = models.CASCADE)
resume = models.CallableFilePathField(path=resume_directory_path, null=True)
The trouble is that I don't know how to properly reference the model instance in this code (so instance is undefined). I've looked at the FileField code to try to see how they do it there, but I couldn't make sense of it.