[Django]-How to cast Django form to dict where keys are field id in template and values are initial values?

1👍

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

Originally added to the question body itself reference.

0👍

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…

0👍

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)

Leave a comment