我想根据 Django 管理员用户提供的字段值将图像上传到媒体根目录。这是我编写的代码,我知道是upload_to 参数导致了问题。但我不知道如何使它工作。
模型.py
class Info(models.Model):
file_no = models.CharField(max_length=100)
date = models.DateField()
area = models.IntegerField(default=0.00)
mouja = models.CharField(max_length=100)
doc_type_choices = (
('deed', 'Deed'),
('khotian', 'Khotian'),
)
doc_type = models.CharField(max_length=50,
choices=doc_type_choices,
default='deed')
doc_no = models.CharField(max_length=50)
def __unicode__(self):
return self.file_no
class Image(models.Model):
info = models.ForeignKey('Info')
content = models.ImageField(upload_to=self.info.mouja/self.info.doc_type)
def __unicode__(self):
return self.info.file_no
每当我运行 python manage.py makemigrations 它显示 NameError: name 'self' is not defined在此先感谢您的帮助!
最佳答案
在 upload_to
关键字您需要提供一个您将定义的函数,例如:
def path_file_name(instance, filename):
return '/'.join(filter(None, (instance.info.mouja, instance.info.doc_type, filename)))
class Image(models.Model):
content = models.ImageField(upload_to=path_file_name)
来自 Django documentation: Model field reference :
This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system.
在这个可调用对象中,在特定情况下是
path_file_name
函数,我们从 instance
构建路径字段是 Image
的特定记录模型。filter
函数删除任何 None
列表之外的项目和 join
函数通过用 /
连接所有列表项来构造路径.
关于django - 如何根据Django中的字段名称更改ImageField的upload_to参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30349547/