在自定义验证时提出ValidationError

时间:2016-05-18 19:20:43

标签: python django forms

我在表单中显示错误时遇到问题。

比方说,我的表单有两个字段,只有当它们都是空的时才需要它们,但是当只有一个字段有值时我们不能让它们处理。 所以我试图在视图中进行此验证然后引发异常,一切都没问题,但是错误被引发为带有追溯等的调试页面。

raise utils.ValidationError(u'SOME EXAMPLE TEXT')

这是在视野中。

所以我尝试了其他方式,我已经知道我可以在def清单中进行验证

IN FORM

def clean(self):
    super(forms.Form,self).clean()
    if 'departure_date_time_plain' in self.cleaned_data and 'arrival_date_time_plain' not in self.cleaned_data:
        self._errors['arrival_date_time_plain'] = [u'PUT HERE SOME DATE']

    if 'departure_date_time_plain' not in self.cleaned_data and 'arrival_date_time_plain' in self.cleaned_data:
        self._errors['arrival_date_time_plain'] = [u'PUT HERE SOME DATE']
    return self.cleaned_data

查看我的第二种方法的视图代码:

def new_bus(request, id, id_sec):
    args = {}
    args.update(csrf(request))
    if request.method == 'POST':
        train_form = TrainForm(request.POST)
        args['new_train'] = train_form
        if "train" in request.POST and train_form.is_valid():
            if train_form['reservation_train'].value():
                 train = Train.objects.create(                  
                    transportation=train_form['trans'].value(),
                    number=train_form['num'].value(),                                    
                    departure=train_form['departure_date_time_train'].value(),
                    arrival=train_form['arrival_date_time_train'].value(),
                    reservation=train_form['reservation_train'].value(),
                    seat_number=train_form['seat_number_train'].value(),
                    section_numbers=train_form['section_numbers_train'].value()
                    )
            else:
                 train = Train.objects.create(reservation=False)

           sec = Section.objects.get(id=id_sec)
           sec.locomotion = JourneyType.objects.create(train=train)
           sec.save()
           return HttpResponseRedirect('/trip/'+ id)
    args['new_train'] = TrainForm()
    return render(request, 'add_trip/new_bus.html', args)

这种方法从未被调用过,你能告诉我如何解决这个问题吗?因为我用完了教程和其他任何选项,或者我只是错过了一些东西。我会很感激任何答案

- 答案 -

感谢@Shang Wang的评论,我发现了真正的问题。仅当您的字段为requierd=True时,才会调用Clean,并且由于一个错误而导致我的错误未正确显示:

而不是:

bus_form = BusForm(request.POST)
plain_form = PlainForm(request.POST)
train_form = TrainForm(request.POST)
args['new_bus'] = bus_form
args['new_plain'] = plain_form
args['new_train'] = train_form

我有:

bus_form = BusForm()
plain_form = PlainForm()
train_form = TrainForm()
args['new_bus'] = bus_form
args['new_plain'] = plain_form
args['new_train'] = train_form

1 个答案:

答案 0 :(得分:2)

我认为您的第二种方法的问题是您没有捕获从父cleaned_data方法返回的clean。你也在调用错误的super方法。应该在表单类本身上调用super,而不是从当前类继承的类。我想你应该:

class CurrentForm(forms.Form):

    def clean(self):
        cleaned_data = super(CurrentForm, self).clean()
        if 'departure_date_time_plain' in cleaned_data and 'arrival_date_time_plain' not in cleaned_data:
            self._errors['arrival_date_time_plain'] = [u'PUT HERE SOME DATE']

        if 'departure_date_time_plain' not in cleaned_data and 'arrival_date_time_plain' in cleaned_data:
            self._errors['arrival_date_time_plain'] = [u'PUT HERE SOME DATE']
        return self.cleaned_data

You will always have the best tutorial by checking out django docs