我有一个模特:
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])
我的setFilePath方法是这样的:
def setFilePath(instance, filename):
return 'attendance-record/{course}/{year}/{sec}/{subject}/'.format(course=instance.course, year=instance.year, sec=instance.sec, subject=instance.subject)
但是我不确定这个工作!任何人都可以纠正我,我只希望我的文件目标如此具体,并且这些字段在表的其他列中给出
我已经搜索了如何执行此操作,并找到了一些方法,其中包括使用1.两个Save方法。2. Postgres方式尽管我使用的是postgres,但我希望目录路径与此相同。
根据docs中的示例,您正在使用正确的方法。它不起作用的原因是您没有filename
将路径包括在内。因此解决方案将是:
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)
请注意,默认文件路径长度为100个字符。如果需要增加此值,可以将max_length
参数传递给模型定义,如下所示:
file = models.FileField(upload_to=setFilePath, validators=[validate_file_extension], max_length=256)
谢谢工作!
乐意效劳。请考虑将答案标记为已接受。