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