Files
tripwithbonus/AuthApp/forms.py
2023-12-15 15:28:29 +03:00

140 lines
5.9 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 *
# from djng.styling.bootstrap3.forms import Bootstrap3ModelForm
# from djng.forms import fields, NgModelFormMixin, NgFormValidationMixin, NgModelForm
# from datetimepicker.widgets import DateTimePicker
# from datetimepicker.helpers import js_loader_url
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True)
class RegistrationForm(forms.Form):
from .models import account_type_choices
# account_type = forms.ChoiceField(choices=account_type_choices, initial='sender', required=True)
firstname = forms.CharField(required=False)
lastname = forms.CharField(required=False)
country = forms.CharField(required=False)
city = forms.CharField(required=False)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput())
confirm_password = forms.CharField(widget=forms.PasswordInput())
tel = forms.CharField()
agreement = forms.BooleanField(initial=False, required=True)
def __init__(self, *args, **kwargs):
required_password = True
required_agreement = True
required_email = True
if 'not_required_password' in kwargs.keys() and kwargs['not_required_password']:
required_password = False
del kwargs['not_required_password']
if 'not_required_agreement' in kwargs.keys() and kwargs['not_required_agreement']:
required_agreement = False
del kwargs['not_required_agreement']
if 'not_required_email' in kwargs.keys() and kwargs['not_required_email']:
required_email = False
del kwargs['not_required_email']
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['password'].required = required_password
self.fields['confirm_password'].required = required_password
self.fields['agreement'].required = required_agreement
self.fields['email'].required = required_email
def clean(self):
cleaned_data = super().clean()
# i = 0
# names = list(cleaned_data.keys())
# while i < len(names):
# if not cleaned_data[names[i]]:
# if self.fields[names[i]].required:
# self.add_error(names[i], _('Обязательное поле'))
# i += 1
if 'tel' in cleaned_data and 'tel' in cleaned_data:
from BaseModels.validators.form_field_validators import get_phone_valid_error
error = get_phone_valid_error(cleaned_data["tel"])
if error:
self.add_error('tel', error)
if cleaned_data and 'confirm_password' in cleaned_data and 'password' in cleaned_data:
if cleaned_data['confirm_password'] != cleaned_data['password']:
self.add_error("password", _('Пароль и подтверждение пароля не совпадают'))
self.add_error("confirm_password", _('Пароль и подтверждение пароля не совпадают'))
if cleaned_data and 'email' in cleaned_data:
users = User.objects.filter(email=cleaned_data['email'])
if users:
self.add_error('email', _("Пользователь с указанным email уже существует"))
# # class PersonForm(NgModelFormMixin, NgFormValidationMixin, NgModelForm, Bootstrap3ModelForm):
# #
# # form_name = 'person_form'
# # scope_prefix = 'person_data'
# #
# # class Meta:
# # model = UserProfile
# # fields = ['name', 'departament', 'company', 'company_position',
# # 'days_to_order_cancellation_default', 'days_to_pay_default',
# # 'pay_terms', 'birthdate',
# # 'phone', 'email', 'discount', 'document_sign_person']
#
#
#
# def emailValid(value):
# if User.objects.filter(username=value, is_active=True):
# raise ValidationError(_(u'пользователь с таким e-mail уже существует, воспользуйтесь восстановлением пароля'))
#
# def check_authorizationBy_cleaned_data(cleaned_data):
# from django.contrib.auth import authenticate
# print('check_authorizationBy_cleaned_data')
# username = cleaned_data.get('username')
# password = cleaned_data.get('password')
#
# user = authenticate(username=username, password=password)
# # print(user)
# if user:
# # if user.is_active:
# return user
#
# def check_activate_by_user(reg_user):
# print('check_activate_by_user')
# if reg_user:
# if reg_user.is_active:
# return True
#
# return False
#
# class LoginForm(AuthenticationForm):
# username = forms.EmailField(label=_('Email'), widget=forms.TextInput())
# password = forms.CharField(min_length=8, label=_('Пароль'), widget=forms.PasswordInput(render_value=False))
#
# def clean(self):
# # print('check')
# cleaned_data = super(LoginForm, self).clean()
# 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 ResetPassword_byEmail_Form(AuthenticationForm):
# email = forms.EmailField(label=_('Email'), widget=forms.TextInput())