我在模型中使用两个日期字段,如下所示。
private void initUser(){
/**
* TODO: Da spostare nella classe Model, o comunque nel package model!!!
*/
FirebaseManager fireManager = FirebaseManager.getInstance();
FirebaseManager.getInstance().getUser(new FirebaseManager.DataSnapshotCallback() {
@Override
public void onResult(DataSnapshot result) {
user = result.getValue(User.class);
}
});
}
我在我的GCBV Create中使用模型表格。我要覆盖表单的class Booking(models.Model):
checkin_date = models.DateField()
checkout_date = models.DateField()
...
方法以在字段之间进行条件验证。
clean()
当我为任一日期输入无效值(例如2018-09- 31 )时,它都会失败并打印堆栈跟踪。
堆栈跟踪:
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
def clean(self):
cleaned_data = super(BookingForm, self).clean()
checkin_date = self.cleaned_data['checkin_date'] # fail here
checkout_date = self.cleaned_data['checkout_date'] # fail here
self.validate_dates(checkin_date, checkout_date)
# GCBV Create
class NewBooking(CreateView):
form_class = BookingForm
model = Booking
1)这是所有表单字段验证的行为,并且仅在File "/home/indikau/workspace/projects/src/booking/forms.py" in clean
67. checkout_date = self.cleaned_data['checkout_date']
Exception Type: KeyError at /booking/add/
Exception Value: 'checkout_date'
方法被覆盖时才会发生吗?
2)如何在不完全失败的情况下克服问题?
答案 0 :(得分:0)
我认为您应该从 cleaned_data
获取数据,而不是从 cleaned_data
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
def clean(self):
cleaned_data = super(BookingForm, self).clean()
checkin_date = cleaned_data.get('checkin_date')
checkout_date = cleaned_data.get('checkout_date')
if checkout_date and checkin_date:
self.validate_dates(checkin_date, checkout_date)