How to distinguish a Django form from a dict, where the keys are the field identifier in the template and the values ​​are initial values?

I have a huge django form and I need to create a dict where the keys are the field identifier in the template and the values ​​are the initial values? Something like that:

{'field1_id_in_template': value1, ...} 

Does anyone know how to do this?

I can add the prefix 'id_' for each field name in the dictionary form.fields, but I may have a problem if someone changes the id for widget.attrs

Answer:

This is the CBV method:

 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 that is the reason why I do this: With this answer I can write something like this on the client. Now I do not need to manually initialize all the fields on the page

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

If you set auto_id to True, you can get the identifier using form_object_instance.field_name.auto_id. With that in mind, you can create your own dict, iterating over the form object.

I'm just wondering why you would need to do this kind of processing since the form object is usually used to encapsulate this behavior ...

0
source

you can try getattr .

For example, you have a known list of keys like

 ['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) 
0
source

Source: https://habr.com/ru/post/1491657/


All Articles