from wtforms.validators import ValidationError from datetime import date def odometer_date_check(form, field): """ Checks that the entered date and odometer of the pitstop is conformant to the existing pitstops. That means, if a pitstops date is between to other pitstops, the odometer should be as well. :param form: :param field: :return: """ odometer = form.odometer.data date = form.date.data pitstops = form.pitstops if date < pitstops[0].date and odometer >= pitstops[0].odometer: raise ValidationError('The new odometer value must be less than %i km' % pitstops[0].odometer) for index in range(0, len(pitstops)-1): if pitstops[index].date <= date < pitstops[index + 1].date: if odometer <= pitstops[index].odometer or odometer >= pitstops[index+1].odometer: raise ValidationError('The new odometer value must be greater than %i km and less than %i km' % (pitstops[index].odometer,pitstops[index+1].odometer)) if date >= pitstops[-1].date and odometer <= pitstops[-1].odometer: raise ValidationError('The new odometer value must be greater than %i km' % pitstops[-1].odometer) def date_check(form, field): """ Checks that the date of the pitstop is not before the date of the latest pitstop and not after today. :param form: the form where the field is in :param field: the field to check :return: Nothing or a ValidationError if the limits are not kept """ if field.data < form.last_pitstop.date: raise ValidationError('The new date must not be before %s' % form.last_pitstop.date) if field.data > date.today(): raise ValidationError('The new date must not be after %s' % date.today()) def odometer_check(form, field): """ :param form: :param field: :return: """ if not form.same_odometer_allowed and field.data <= form.last_pitstop.odometer: raise ValidationError('The new odometer value must be higher than %i km' % form.last_pitstop.odometer) if form.same_odometer_allowed and field.data < form.last_pitstop.odometer: raise ValidationError('The new odometer value must be higher than %i km' % form.last_pitstop.odometer) def litres_check(form, field): if field.data is not None and field.data <= 0: raise ValidationError('You must fuel at least 0.1 l') def costs_check(form, field): if field.data is not None and field.data <= 0: raise ValidationError('Costs must be above 0.01 €.') def edit_costs_check(form, field): """ Costs must be given, if a default value was given to the form field. :param form: :param field: :return: """ costs_check_required = (form.costs.default is not None and form.costs.default > 0) if costs_check_required and field.data is not None and field.data <= 0: raise ValidationError('Costs must be above 0.01 €.')