在Django表单显示中没有显示错误

时间:2012-06-14 14:52:56

标签: django django-forms django-templates django-views

无法判断我做错了什么。当我发布我的表单时,有很多缺少的字段。它会重新显示但不会打印错误。下面是表单,视图和模板

我有一个模型表格:

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

观点:

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))

模板:

{% 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 %}            

1 个答案:

答案 0 :(得分:2)

当您的表单未通过is_valid时,您将回到此代码:

try:
    hotel = Hoteloffer.objects.get(pk=hotel_id)
    f = HotelOfferForm(instance=hotel)
except:
    f = HotelOfferForm()

如果您希望显示包含错误的表单,则应返回包含request.POST作为参数的表单

我还建议调查Django的基于类的视图,特别是UpdateView可以很好地处理这种编辑视图