Django form - Calling is_valid() in a template -
i'm using django 1.5. have template multiple forms: 1 driver has many cars (inline forms). want display hint indicating section contains errors.
the template:
{% if driver_form.is_bound , not driver_form.is_valid %} please correct errors in driver data. {% endif %} {% if car_form.is_bound , not car_form.is_valid %} please correct errors in car data. {% endif %}
the problem if first form invalid, second message pops well, though second form valid. noticed if put {{ car_form.is_valid }}
3 times in row, first time empty, next time (and following) true
.
the original view:
if request.method == 'post': driver_form = drivermodelform(request.post) car_form_set = carinlineformset(request.post) # wrong: no instance passed if driver_form.is_valid(): driver = driver_form.save(commit=false) car_form_set = carinlineformset(request.post, instance=driver) if car_form_set.is_valid(): driver.save() car_form_set.save() else: driver_form = drivermodelform() car_form_set = carinlineformset() return render(request, 'template.html', { 'driver_form': driver_form, 'car_form_set': car_form_set })
update:
it seems simplicity's sake left out details caused problem. lesson learned.
there javascript setting values on page load, while needed done on dropdown change. hiding erroneous values , causing form valid next time around.
there dependency:
driver_form
model form, ,car_form_set
inline form set based on instancedriver_form
adding.
the problem indeed in view, seddonym suggested: car_form_set
not being initialized instance if driver_form
invalid. is_valid()
neither true
nor false
. conclusion: using is_valid()
in template works fine.
the fixed view:
driver = driver() if request.method == 'post': driver_form = drivermodelform(request.post, instance=driver) if driver_form.is_valid(): driver = driver_form.save(commit=false) car_form_set = carinlineformset(request.post, instance=driver) if car_form_set.is_valid(): driver.save() car_form_set.save() else: driver_form = drivermodelform(instance=driver) car_form_set = carinlineformset(instance=driver) return render(request, 'template.html', { 'driver_form': driver_form, 'car_form_set': car_form_set })
you don't need call form.is_valid, have been called view. instead, check errors:
{% if first_form.errors %} please correct errors in first form. {% endif %} {% if second_form.errors %} please correct errors in second form. {% endif %}
Comments
Post a Comment