How to cast Django form to dict where keys are fie

2020-07-18 06:21发布

问题:

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(); 
    } 
} 

回答1:

If you have the auto_id set to True then you can get the id with form_object_instance.field_name.auto_id. With that in mind you can create your dict by iterating over the form object.

I am just wondering why you would need to do such a processing as the form object is usually used to encapsulate such behaviors...



回答2:

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)