在__init__方法中设置初始Django表单域值 [英] Setting initial Django form field value in the __init__ method

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

问题描述

Django 1.6

Django 1.6

我在Django表单类中有一个工作的代码块,如下所示。我正在构建表单域列表的数据集可以包含任何字段的初始值,并且我在表单中设置初始值没有成功。如果field_value:块下面的确实填充了初始表单字典属性,但初始值未显示。请注意,如果您想知道, .initial 属性在 super()调用之前不存在。

I have a working block of code in a Django form class as shown below. The data set from which I'm building the form field list can include an initial value for any of the fields, and I'm having no success in setting that initial value in the form. The if field_value: block below does indeed populate the initial form dictionary attribute, but the initial value is not being displayed. Note that (in case you are wondering) the .initial attribute does not exist until after the super() call.

可以这样做吗?

如果是这样,我没有做正确的工作吗?

If so, what I'm not doing right to make this work?

谢谢!

def __init__(self, *args, **kwargs):
    id = kwargs.pop('values_id', 0)
    super(LaunchForm, self).__init__(*args, **kwargs)
    # Lotsa code here that uses the id value
    # to execute a query and build the form
    # fields and their attributes from the 
    # result set

    if field_value:
        self.initial[field_name] = field_value


推荐答案

同样的问题,我解决了这样做:

I had that exact same problem and I solved it doing this:

def __init__(self, *args, **kwargs):
    instance = kwargs.get('instance', None)

    kwargs.update(initial={
        # 'field': 'value'
        'km_partida': '1020'
    })

    super(ViagemForm, self).__init__(*args, **kwargs)

    # all other stuff

这篇关于在__init__方法中设置初始Django表单域值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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