更改模型管理表单默认值 [英] change model admin form default value

查看:138
本文介绍了更改模型管理表单默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中有典型的模型继承:

  class A(models.Model):
boolean_field = models.BooleanField(default = True)

class B(A):
some_other_field = models.CharField()

我想覆盖类 B 中的默认值 boolean_field 我怎么能这样做?



我认为在数据库层可能会很棘手的事情,所以也许至少我可以简单地覆盖Django中的默认值我的意思是在 ModelAdmin 表单中的类 B )。

解决方案

根据您的建议,我认为最简单的方法是在django管理员中更改用于 B 模型的模型。 / p>

要更改表单字段的初始值,您可以重新定义该字段,或覆盖 __ init __ 方法。

  class BForm(forms.ModelForm):
#重新定义布尔字段
boolean_field = models。 BooleanField(ini​​tial = False)

class Meta:
model = B

#或覆盖__init__方法并设置initial = False
#这是有点复杂但重复性较差
def __init __(self,* args,** kwargs):
super(BForm,self).__ init __(* args,** kwargs)
self。字段['boolean_field']。initial = False

在django管理中使用您的自定义模型表单很简单!

  class BAdmin(admin.ModelAdmin):
form = BForm

admin。 site.register(B,BAdmin)


I have typical model inheritance in my project:

class A(models.Model):
    boolean_field = models.BooleanField(default=True)

class B(A):
    some_other_field = models.CharField()

I want to override default value of boolean_field in class B, how can I do it?

I think that could be tricky thing to do on a database layer, so maybe at least I can simply override that default value in Django admin (I mean in ModelAdmin form for class B).

解决方案

As you suggest, I think the easiest approach is to change the model form used for the B model in the django admin.

To change the initial value of the form field, you can either redefine the field, or override the __init__ method.

class BForm(forms.ModelForm):
    # either redefine the boolean field
    boolean_field = models.BooleanField(initial=False)

    class Meta:
        model = B

    # or override the __init__ method and set initial=False
    # this is a bit more complicated but less repetitive
    def __init__(self, *args, **kwargs):
        super(BForm, self).__init__(*args, **kwargs)
        self.fields['boolean_field'].initial = False

Using your custom model form in the django admin is easy!

class BAdmin(admin.ModelAdmin):
    form = BForm

admin.site.register(B, BAdmin)

这篇关于更改模型管理表单默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆