【问题标题】:Django 1.8 Fails migration with dynamic upload_to over a FileFieldDjango 1.8 在 FileField 上使用动态 upload_to 迁移失败
【发布时间】:2015-08-17 21:53:55
【问题描述】:

在尝试对具有动态 upload_to 路径的 FileField 的模型使用迁移时,我遇到了以下错误。

    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)

【问题讨论】:

  • 删除迁移文件并再次运行makemigrations
  • 由于upload_path() 函数不在一个类中,它不应该有第一个参数self,而是看起来像def upload_path(instance, filename)。您以前是否尝试过在课堂上使用它?错误消息还建议在那里而不是在core.models.upload_path 中搜索。
  • @Leistungsabfall 没用。
  • @sthzg 是的,这是之前尝试的错误,但这不是问题
  • 是这样想的。将update_path 拉到模块外部后,异常是否保持不变?因为它会从打印的内容中搜索 upload_path 内部的可调用 UserProfile

标签: python django django-models django-migrations


【解决方案1】:

您可以使用@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)

阅读更多:

【讨论】:

  • 这是一个老问题,但我偶然发现了它,并认为它可能对其他人有用:)
猜你喜欢
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
相关资源
最近更新 更多