【问题标题】:Not getting error display in Django form display在 Django 表单显示中没有得到错误显示
【发布时间】:2012-06-14 14:52:55
【问题描述】:

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

我有一个模型表格:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    如果您想显示带有错误的表单,它应该返回带有 request.POST 作为参数的表单

    我还建议研究 Django 的基于类的视图,尤其是 UpdateView 可以很好地与这种编辑视图配合使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-12
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 2021-08-10
      • 2016-07-12
      相关资源
      最近更新 更多