Files
2025-02-28 15:42:44 +03:00

128 lines
6.6 KiB
Python
Raw Permalink 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 .funcs import get_cargo_types_by_type_transport
from .models import *
import copy
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, owner_type, *args, **kwargs):
super(RouteForm, self).__init__(*args, **kwargs)
self.fields['from_city'].required = True
self.fields['to_city'].required = True
self.fields['type_transport'].required = True
data = None
if kwargs and 'data' in kwargs:
data= kwargs['data']
if owner_type == 'mover':
self.fields['departure_DT'].required = True
self.fields['type_transport'].choices = type_transport_choices[:-1]
else:
self.fields['type_transport'].choices = type_transport_choices
cargo_types = copy.deepcopy(cargo_type_choices)
if data and 'type_transport' in data and data['type_transport'] == 'avia':
cargo_types = cargo_types[:2] + cargo_types[3:]
self.fields['cargo_type'].choices = cargo_types
def clean(self):
# print('check')
cleaned_data = super(RouteForm, self).clean()
try:
if 'type_transport' in self.errors:
if self.instance and self.instance.owner_type == 'customer':
self.errors.pop('type_transport')
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)
cleaned_data['phone'] = self.data['phone']
# 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'] and cleaned_data['departure_DT']
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)