Warm tip: This article is reproduced from stackoverflow.com, please click
django django-models

Django- Creating a dynamic path for file upload in models.py

发布于 2020-03-27 15:45:33

I am having a model :

class Attendance(models.Model):
    course = models.CharField(max_length=30)
    year = models.IntegerField(_('year'), choices=year_choices, default=current_year)
    sec = models.CharField(max_length=10)
    subject = models.CharField(max_length=30)
    file = models.FileField(upload_to=setFilePath, validators=[validate_file_extension])

and my setFilePath method goes like this :

def setFilePath(instance, filename):
    return 'attendance-record/{course}/{year}/{sec}/{subject}/'.format(course=instance.course, year=instance.year, sec=instance.sec, subject=instance.subject)

but I am not sure of this working ! Can anyone correct me, I want my file destination to be specific like this only and those fields are given in other column of tables


I have searched how to do this and found some ways which includes using 1. two Save method 2. Postgres way Though I am using postgres I want the dir path to be same as this.

Questioner
sudipt dabral
Viewed
20
Daniel Holmes 2020-01-31 17:05

Based on the example in the docs, you are using the right approach. The reason why it is not working is that you have not included the filename in the path. So the solution would be:

def setFilePath(instance, filename):
    return 'attendance-record/{course}/{year}/{sec}/{subject}/{filename}'.format(course=instance.course, year=instance.year, sec=instance.sec, subject=instance.subject, filename=filename)

Note that the default file path length is 100 characters. If you need to increase this, you can pass a max_length argument to your model definition, like so:

file = models.FileField(upload_to=setFilePath, validators=[validate_file_extension], max_length=256)