Django - 如何在页面上显示错误而不是显示错误500页?

时间:2016-01-09 15:09:02

标签: django

我有自定义验证的预订模型。当我提交表单使得持续时间为0并引发ValidationError时,它会使用此消息将我引导到Django Debug / Traceback页面

ValidationError at /management
{'__all__': [u'Duration cannot be 0.']}

我如何才能使消息与表单本身一起显示?

models.py

class Booking(models.Model):
    duration = models.FloatField(default=1) # duration in hours
    def clean(self, *args, **kwargs):
        if self.duration == 0:
             raise ValidationError('Duration cannot be 0.')
        super(Booking, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Booking, self).save(*args, **kwargs)

views.py

def management(request):
    if request.method == "POST":
         form = ManagementBookingForm(request.POST)
         if form.is_valid():
             duration = form.cleaned_data['duration']
             booking = Booking(duration=duration)
             booking.save()
             return redirect('management')
         else:
            context = {}
            context['booking_form'] = form
            messages.error(request, 'Errors were found in the form')
            return render(request, 'bookings/management.html', context)

1 个答案:

答案 0 :(得分:1)

由于(由于您不会解释的原因)您没有使用ModelForm,因此您不能在此依赖模型验证:您需要使用表单验证。将clean方法移动到Form子类,并从django.forms导入ValidationError。