0

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.

3
  • So is your question as to whether or not this will work, or if this is the right approach? Commented Jan 31, 2020 at 8:10
  • Also, are you intentionally wanting to leave out the filename in the filepath? I don't think that will work Commented Jan 31, 2020 at 8:13
  • Right approach and it is no working btw! Thanks @Daniel Commented Jan 31, 2020 at 8:53

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.