在ModelForm中覆盖初始值 [英] Overriding initial value in ModelForm

查看:121
本文介绍了在ModelForm中覆盖初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django(1.2)项目中,我想在模型窗体中预先填充一个字段,但是我的新值将被忽略。
这是片段:

  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屋!

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