在ModelForm中覆盖初始值 [英] Overriding initial value in ModelForm
本文介绍了在ModelForm中覆盖初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是片段:
class ArtefactForm(ModelForm):
material = CharField(widget = AutoCompleteWidget ('material',force_selection = False))
def __init __(self,* args,** kwargs):
super(ArtefactForm,self).__ init __(* args,** kwargs )
self.fields ['material']。initial ='Test'
我也尝试使用 self.base_fields
,但不起作用:表单中总是显示数据库值。任何想法?
解决方案
尝试这样:
code> def __init __(self,* args,** kwargs):
initial = kwargs.get('initial',{})
initial ['material'] ='Test'
kwargs ['initial'] = initial
super(ArtefactForm,self).__ init __(* args,** kwargs)
in my Django (1.2) project, I want to prepopulate a field in a modelform, but my new value is ignored. This is the snippet:
class ArtefactForm(ModelForm):
material = CharField(widget=AutoCompleteWidget('material', force_selection=False))
def __init__(self, *args, **kwargs):
super(ArtefactForm, self).__init__(*args, **kwargs)
self.fields['material'].initial = 'Test'
I also tried with self.base_fields
, but no effect: there is always the database-value displaying in the form. Any ideas?
解决方案
Try this:
def __init__(self, *args, **kwargs):
initial = kwargs.get('initial', {})
initial['material'] = 'Test'
kwargs['initial'] = initial
super(ArtefactForm, self).__init__(*args, **kwargs)
这篇关于在ModelForm中覆盖初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文