Can’t figure what I am doing wrong. When I post my form there are lots of missing fields. It redisplays but doesn’t print errors. Below is form, view and template
I have a model form:
class HotelOfferForm(forms.ModelForm):
"""
form for Ensemble personel to complete to make offer live
"""
class Meta:
model = Hoteloffer
widgets = {
'standard_Service': forms.CheckboxSelectMultiple(),
'leisure_Service': forms.CheckboxSelectMultiple(),
'dining_Service': forms.CheckboxSelectMultiple(),
'lto_start_date': SelectDateWidget(),
'lto_end_date': SelectDateWidget(),
}
And a view:
def edit_hotel(request, hotel_id):
print 'in edit_hotel'
if request.method == 'POST':
print "in POST"
print hotel_id, type(hotel_id)
if int(hotel_id) != 0:
print 'got hotel_id', hotel_id
hotel = Hoteloffer.objects.get(pk=hotel_id)
f = HotelOfferForm(request.POST, instance=hotel)
else:
print 'no hotel id available'
f = HotelOfferForm(request.POST)
print "Is it valid?", f.is_valid()
if f.is_valid():
hotel = f.save()
return redirect("/hotels/list_hotels/", context_instance=RequestContext(request))
try:
hotel = Hoteloffer.objects.get(pk=hotel_id)
f = HotelOfferForm(instance=hotel)
except:
f = HotelOfferForm()
print "about to render", f.errors # ******* prints nothing???
return render_to_response('hotels/hotel_form.html', {'f': f, 'title': hotel.title}, context_instance=RequestContext(request))
template:
{% extends 'base.html' %}
{% block title %}Ensemble Travel Group Offer Entry System: Hotel {{title}}{% endblock %}
{% block content %}
<!--{{ f.name }} {{f.errors}}-->
<!-- am i here? -->
<h2>{{ title }}</h2>
{% if f.errors %}
<p style="color: red;">
Please correct the error{{ f.errors|pluralize }} below.
{{ f.errors }}
</p>
{% endif %}
<form action="" method="post">{% csrf_token %}
<table>
{{ f.as_table }}
</table>
<input type='submit' id='submit' name='submit' value='Submit' />
</form>
{% endblock %}
When your form does not pass is_valid you are falling back to this code:
If you want to show the form with it’s errors it should be returning the form with
request.POSTas an argumentI would also advise to look into Django’s Class Based Views, especially UpdateView would work nicely with this kind of edit views