Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django 1.8无法通过文件字段将动态上载到迁移_Python_Django_Django Models_Django Migrations - Fatal编程技术网

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 in
UserProfile
。这是一个老问题,但我偶然发现了它,并认为让别人回答它可能会有用:)