如何在Django中加载自定义字段

问题描述:

注意:这与该问题的答案密切相关:

在Django中,可以创建具有不属于任何模型中特定数据库字段的胭脂字段的自定义ModelForm。

In Django it is possible to create custom ModelForms that have "rouge" fields that don't pertain to a specific database field in any model.

在以下代码示例中,有一个名为 extra_field的自定义字段。它显示在其模型实例的管理页面中,可以通过save方法进行访问,但似乎没有加载方法。

In the following code example there is a custom field that called 'extra_field'. It appears in the admin page for it's model instance and it can be accessed in the save method but there does not appear to be a 'load' method.

我该如何加载 extra_field与管理页面之前的数据?

How do I load the 'extra_field' with data before the admin page loads?

# admin.py
class YourModelForm(forms.ModelForm):
    extra_field = forms.CharField()

    def load(..., obj):
        # This method doesn't exist.
        # extra_field = obj.id * random()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

class YourModelAdmin(admin.ModelAdmin):
    form = YourModelForm
    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

源代码@vishnu

覆盖表单的 __ init __ 方法并设置 initial 属性:

Override the form's __init__ method and set the initial property of the field:

class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        initial = '%s*rnd' % self.instance.pk if self.instance.pk else 'new'
        self.fields['extra_field'].initial = initial