如何在Django中加载自定义字段 [英] How do you load a custom field in 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 __
方法并设置<$ c $字段的c> 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
这篇关于如何在Django中加载自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!