注意:这与此问题的答案密切相关: django admin - add custom form fields that are not part of the model
在Django中,可以创建具有" rouge"的自定义ModelForms。不属于任何模型中特定数据库字段的字段。
在下面的代码示例中,有一个名为' extra_field'的自定义字段。它出现在它的模型实例的管理页面中,并且可以在保存方法中访问它,但似乎没有“加载”#39;方法
如何加载' extra_field'管理页面加载前的数据?
# 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的源代码
答案 0 :(得分:2)
覆盖表单的__init__
方法并设置字段的initial
属性:
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