如何将Django表单转换为dict,哪些键是模板中的字段ID,值是初始值? [英] How to cast Django form to dict where keys are field id in template and values are initial values?

查看:100
本文介绍了如何将Django表单转换为dict,哪些键是模板中的字段ID,值是初始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的django形式,我需要创建dict,其中keys是模板中的字段id,值是初始值?
这样的东西:

  {'field1_id_in_template':value1,...} 

有人知道怎么做吗?



我可以添加前缀'id_ '对于form.fields字典中的每个字段名称,但如果有人更改了widget.attrs的id,我可以有问题



答案: p>

这是CBV的方法:

  def post_ajax(self,request, * args,** kwargs):
form = ChooseForm(request.POST,log = log)
如果form.is_valid():
instance = form.save()
inst_form = InstanceForm(instance = instance,account = request.user)
fields = {}
在inst_form.fields中的名称:
如果inst_form.initial中的名称:
fields [ inst_form.auto_id%name] = inst_form.initial [name]
return HttpResponse(
json.dumps({'status':'OK','fields':fields},
mimetype = appplication / json'

assert False

这就是为什么我这样做:
有了这个响应,我可以在客户端上写这样的东西。现在我不需要手动初始化页面上的所有字段

  function mergeFields(data){
for var id in data){
$(#+ id).val(data [id])。change();
}
}


解决方案

你可以尝试 getattr



例如,您有一个已知的密钥列表为

  ['field1_id_in_template','field2_id_in_template',...] 

然后:

  my_values = dict()
key_list中的键:
value = getattr your_form,key)
#现在用它做某事
my_values [key] = deal_with(value)


I have a huge django form and I need to create dict where keys are field id in template and values are initial values? Something like this:

{'field1_id_in_template': value1, ...}

Does somebody know how do that?

I can add prefix 'id_' for each field name in form.fields dictionary but I can have a problem if somebody change id for widget.attrs

Answer:

This is method of CBV:

def post_ajax(self, request, *args, **kwargs):
    form = ChooseForm(request.POST, log=log)
    if form.is_valid():
        instance = form.save()
        inst_form = InstanceForm(instance=instance, account=request.user)
        fields = {}
        for name in inst_form.fields:
            if name in inst_form.initial:
                fields[inst_form.auto_id % name] = inst_form.initial[name]
        return HttpResponse(
            json.dumps({'status': 'OK','fields':fields},
            mimetype='appplication/json'
        )
    assert False

And this a reason why I do that: With this response I can write something like this on client. Now I don't need to manualy initialize all fields on the page

function mergeFields(data) { 
    for(var id in data) { 
        $("#"+id).val(data[id]).change(); 
    } 
} 

解决方案

you can try getattr.

For example, you have a known key list as

['field1_id_in_template', 'field2_id_in_template', ...]

Then:

my_values = dict()
for key in key_list:
    value = getattr(your_form, key)
    # now do something with it
    my_values[key] = deal_with(value)

这篇关于如何将Django表单转换为dict,哪些键是模板中的字段ID,值是初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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