【问题标题】:Model method to generate the value for a parameter of an attribute为属性的参数生成值的模型方法
【发布时间】:2021-05-18 02:08:11
【问题描述】:

我想在模型中创建一个方法,该方法可以在属性的参数上调用以填充它。我想过这样做,但它给了我一个错误NameError: name 'self' is not defined

class Host(User):
    class Meta:
        verbose_name = "Host"
        verbose_name_plural = "Hosts"
    def gen_path(self):
        path = 'static/{userdir}'.format(userdir=self.email)
        os.mkdir(path)
        return path
    hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=self.gen_path(), null=True)

有什么办法可以解决这个问题?

【问题讨论】:

    标签: django django-models django-rest-framework


    【解决方案1】:

    您可以创建将instancefilename 作为upload_to 属性参数的方法;

    def gen_path(instance, filename):
        extension = filename.split(".")[-1]
        filename = f"{instance.email}.{extension}"
        return f"static/{filename}"
    
    
    class Host(User):
        hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=gen_path, null=True)
    
        class Meta:
            verbose_name = "Host"
            verbose_name_plural = "Hosts"
    

    更多信息see docs

    【讨论】:

      【解决方案2】:

      尝试使用这个:

      您应该插入一个文件夹名称来保存图像,例如:-

      hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to='hostimages', null=True)
      

      【讨论】:

      • 不,我需要动态保存路径。
      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 2011-12-07
      • 2018-08-06
      • 2013-02-16
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2013-11-12
      相关资源
      最近更新 更多