Files
tripwithbonus/RoutesApp/forms.py
2025-01-10 21:48:20 +03:00

136 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# # coding=utf-8
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from .models import *
def routeForm_assign_choices_by_type_transport(form, type_transport):
if type_transport == 'avia':
transfer_location_choices = (
('airport', _('В аэропорту')),
('city', _('По городу')),
('other', _('По договоренности'))
)
cargo_type_choices = (
('cargo', _('Груз')),
('parcel', _('Бандероль')),
('package', _('Посылка')),
('letter', _('Письмо\Документ'))
)
else:
transfer_location_choices = (
('city', _('По городу')),
('other', _('По договоренности'))
)
cargo_type_choices = (
('passenger', _('Пассажир')),
('cargo', _('Груз')),
('parcel', _('Бандероль')),
('package', _('Посылка')),
('letter', _('Письмо\Документ'))
)
form.fields['from_place'].choices = transfer_location_choices
form.fields['to_place'].choices = transfer_location_choices
form.fields['cargo_type'].choices = cargo_type_choices
form.base_fields['from_place'].choices = transfer_location_choices
form.base_fields['to_place'].choices = transfer_location_choices
form.base_fields['cargo_type'].choices = cargo_type_choices
return form
class RouteForm(forms.ModelForm):
# from_address_point_txt = forms.CharField(required=True)
# to_address_point_txt = forms.CharField(required=True)
departure_DT = forms.DateField(required=False, input_formats=['%d.%m.%Y'])
arrival_DT = forms.DateField(required=True, input_formats=['%d.%m.%Y'])
class Meta:
model = Route
exclude = [
'name', 'name_plural', 'order', 'createDT', 'modifiedDT', 'enable', 'json_data',
'receive_msg_by_sms', 'owner', 'owner_type',
'extra_phone', 'weight', 'from_address_point', 'to_address_point',
'from_place', 'to_place', 'receive_msg_by_sms'
]
def __init__(self, *args, **kwargs):
super(RouteForm, self).__init__(*args, **kwargs)
self.fields['from_city'].required = True
self.fields['to_city'].required = True
def clean(self):
# print('check')
cleaned_data = super(RouteForm, self).clean()
try:
if 'phone' in cleaned_data and 'phone' in cleaned_data:
from BaseModels.validators.form_field_validators import get_phone_valid_error
error = get_phone_valid_error(cleaned_data["phone"])
if error:
self.add_error('phone', error)
# if 'extra_phone' in cleaned_data and 'extra_phone' in cleaned_data:
# from BaseModels.validators.form_field_validators import get_phone_valid_error
# error = get_phone_valid_error(cleaned_data["extra_phone"])
# if error:
# self.add_error('extra_phone', error)
if 'departure_DT' in cleaned_data and 'arrival_DT' in cleaned_data and cleaned_data['arrival_DT'] < cleaned_data['departure_DT']:
self.add_error('arrival_DT', _('Указана неверная дата прибытия'))
if 'from_place' in self.data and self.data['from_place'] not in [item[0] for item in self.fields['from_place'].choices]:
cleaned_data['from_place'] = self.fields['from_place'].choices[0][0]
if 'from_place' in self.errors and self.errors['from_place'].data[0].code == 'invalid_choice':
del self.errors['from_place']
if 'to_place' in self.data and self.data['to_place'] not in [item[0] for item in self.fields['to_place'].choices]:
cleaned_data['to_place'] = self.fields['to_place'].choices[0][0]
if 'to_place' in self.errors and self.errors['to_place'].data[0].code == 'invalid_choice':
del self.errors['to_place']
if 'cargo_type' in self.data and self.data['cargo_type'] not in [item[0] for item in self.fields['cargo_type'].choices]:
cleaned_data['cargo_type'] = self.fields['cargo_type'].choices[0][0]
if 'cargo_type' in self.errors and self.errors['cargo_type'].data[0].code == 'invalid_choice':
del self.errors['cargo_type']
except Exception as e:
print(str(e))
# reg_user = check_authorizationBy_cleaned_data(cleaned_data)
# # print(reg_user)
# if not reg_user:
# raise ValidationError(_(u'Пользователь с введенными регистрационными данными не зарегистрирован. Проверьте правильность ввода e-mail и пароля.'))
# else:
# if not check_activate_by_user(reg_user):
# raise ValidationError(_(u'Указанная учетная запись не была Активирована'))
return cleaned_data
# class RegistrationForm(forms.Form):
# type_transport = forms.ChoiceField(choices=type_transport_choices, initial='avia', required=True, label='Выберите способ перевозки')
# departure_DT = forms.DateTimeField(required=True, label='Дата и время выезда')
# arrival_DT = forms.DateTimeField(required=True, label='Дата и время прибытия')
# from_country = forms.CharField(required=True, label='Пункт выезда')
# to_country = forms.CharField(required=True, label='Пункт приезда')
# # from_city = forms.CharField(required=True)
# # to_city = forms.CharField(required=True)
# from_place = forms.ChoiceField(choices=transfer_location_choices, initial='other', required=True, label='Откуда можете забрать?')
# to_place = forms.ChoiceField(choices=transfer_location_choices, initial='other', required=True, label='Куда можете доставить?')
# cargo_type = forms.ChoiceField(choices=cargo_type_choices, initial='parcel', required=True, label='Могу перевезти')
# weight = forms.IntegerField(required=True, label='Укажите вес до (кг)')
# phone = forms.CharField(required=True, label='Укажите номер для связи')
# add_phone = forms.CharField(required=True, label='Дополнительный номер')
# receive_msg_by_email = forms.BooleanField(initial=False, required=True, label='Получать уведомления по E-mail')
# # receive_msg_by_sms = forms.BooleanField(initial=False, required=True)
# # owner = forms.IntegerField(required=True)