1
我有問題在窗體中顯示一個錯誤。提到驗證錯誤,當涉及到自定義驗證
讓我說,我的表單有兩個字段,只有當它們都是空的時候才需要,但是當只有一個字段有值時,我們不能讓情況出現。 所以我試圖做到這一點的驗證在視圖,然後拋出一個異常,一切都是好的,但引發錯誤的調試頁面,追蹤等
raise utils.ValidationError(u'SOME EXAMPLE TEXT')
這是在視圖中。
所以,我想其他辦法,我已經readed,我可以在形式上做驗證的高清清潔
形式
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王的意見,我發現了什麼是真正的問題。清潔是要打電話,只有當你的領域是requierd=True
,我的錯誤是顯示不正確,因爲一個錯誤:
相反的:
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
不幸的是我沒有幫助,這仍然不是事件調用。就像它不存在一樣。 – Yurrili
views.py中的'train_form.is_valid()'會在窗體中調用'clean'方法。你能確保'is_valid'被執行嗎? –
is_valid被執行。在調試中,它進入is_valid,然後在錯誤()中,如果調用self.full_clean(),則它不會進入步驟。 _errors不是None,但它有len 0. – Yurrili