Python Django 1.8无法通过文件字段将动态上载到迁移
当我试图在一个具有动态上传路径的文件字段的模型上使用迁移时,我遇到了以下错误Python Django 1.8无法通过文件字段将动态上载到迁移,python,django,django-models,django-migrations,Python,Django,Django Models,Django Migrations,当我试图在一个具有动态上传路径的文件字段的模型上使用迁移时,我遇到了以下错误 field=models.FileField(null=True, upload_to=core.models.UserProfile.upload_path, blank=True), AttributeError: type object 'UserProfile' has no attribute 'upload_path' 我的代码: def upload_path(instance, filenam
field=models.FileField(null=True, upload_to=core.models.UserProfile.upload_path, blank=True),
AttributeError: type object 'UserProfile' has no attribute 'upload_path'
我的代码:
def upload_path(instance, filename):
return os.path.join(str(instance.user.id),filename)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
document_upload = models.FileField(upload_to=upload_path,null=True, blank=True)
您可以使用@deconstructor类装饰器,这允许迁移子系统序列化装饰的类 范例
from django.utils.deconstruct import deconstructible
@deconstructible
class UploadPath(object):
def __call__(self, instance, filename):
return os.path.join(str(instance.user.id),filename)
upload_path= UploadPath()
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
document_upload = models.FileField(upload_to=upload_path, null=True, blank=True)
阅读更多:
- 相关主题:
- 关于@deconstruct的文档:
makemigrations
。由于upload\u path()
函数不在类内,因此它不应该具有第一个参数self
,而是看起来像def upload\u path(实例,文件名)
。你以前有没有在课堂上尝试过?错误消息还建议在那里搜索,而不是在core.models.upload\u path
@Leistungsabfall中搜索,但该路径无效。@sthzg是的,这是以前尝试的错误,但这不是问题所在。将update\u path
拉到模块外部后,异常是否保持完全相同?因为它从打印的内容中搜索upload\u路径
callable inUserProfile
。这是一个老问题,但我偶然发现了它,并认为让别人回答它可能会有用:)