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