如何使具有模型关系字段的预填充字段?

时间:2019-06-06 07:30:47

标签: python django

我尝试在管理类中添加 prepopulated_fields

class ProfileAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ('get_trainer_name',)}

    def get_trainer_name(self, obj):
        return obj.user.get_full_name()

但出现错误

ERRORS:
<class 'trainers.admin.ProfileAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'get_trainer_name', which is not an attribute of 'trainers.Profile'.

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', null=True)
    slug = models.SlugField()

我也尝试用另一种方法-覆盖模型保存方法:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', null=True)
    slug = models.SlugField()
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.user.get_full_name())
            super(Profile, self).save(*args, **kwargs)

但是没有结果。

按照我尝试在ProfileAdmin上提出的建议@Tiger_Mike

def get_form(self, request, obj=None, **kwargs):
    form = super(ProfileAdmin, self).get_form(request, obj, **kwargs)
    if not obj.slug:
        obj.slug = slugify(obj.user.get_full_name())
    return form

它不能与slugify一起使用,但是没有slugify可以很好地工作

1 个答案:

答案 0 :(得分:0)

只需快速浏览一下管理文档,this hook就可以完成工作。