/
Demek
/
DSam621
Обзор
Документация
Войти
/
Demek
/
DSam621
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
Python/archaeology_project/apps/core/forms.py
364 строки
13 KB
d_e_m_e_k
еще одно видение проекта по археологии
3 часа назад
3 часа назад
8c2f6c8
Код
Авторство
О чём код?
from django import forms from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.forms import inlineformset_factory from .models import ( Excavation, Square, Pit, LepnayaCeramics, EarlyCircularCeramics, DevelopedCircularCeramics, LateCircularCeramics, UndefinedFragments ) # ============================================================ # ФОРМЫ АУТЕНТИФИКАЦИИ # ============================================================ class RegistrationForm(forms.Form): """Форма регистрации""" username = forms.CharField( max_length=150, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Имя пользователя' }) ) email = forms.EmailField( widget=forms.EmailInput(attrs={ 'class': 'form-control', 'placeholder': 'Email' }) ) password = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Пароль' }) ) password_confirm = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Подтверждение пароля' }) ) def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): raise ValidationError('Пользователь с таким именем уже существует') return username def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise ValidationError('Пользователь с таким email уже существует') return email def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') password_confirm = cleaned_data.get('password_confirm') if password and password_confirm and password != password_confirm: raise ValidationError('Пароли не совпадают') if password: try: validate_password(password) except ValidationError as e: raise ValidationError(' '.join(e.messages)) return cleaned_data class LoginForm(forms.Form): """Форма входа""" username = forms.CharField( max_length=150, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Имя пользователя' }) ) password = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Пароль' }) ) remember_me = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={ 'class': 'form-check-input' }) ) class ProfileForm(forms.ModelForm): """Форма редактирования профиля""" class Meta: model = User fields = ['first_name', 'last_name', 'email'] widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), } class ChangePasswordForm(forms.Form): """Форма смены пароля""" old_password = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control'}) ) new_password = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control'}) ) new_password_confirm = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control'}) ) def clean_new_password(self): password = self.cleaned_data.get('new_password') try: validate_password(password) except ValidationError as e: raise ValidationError(' '.join(e.messages)) return password # ============================================================ # ФОРМЫ ДЛЯ МОДЕЛЕЙ # ============================================================ class BaseCeramicsForm(forms.ModelForm): """Базовый класс для форм керамики""" class Meta: abstract = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].label = '' if field != 'color_type': self.fields[field].required = False if isinstance(self.fields[field].widget, forms.NumberInput): self.fields[field].widget.attrs.update({ 'min': '0', 'class': 'form-control form-control-sm', 'step': '1' }) else: self.fields[field].required = True self.fields[field].widget.attrs.update({ 'class': 'form-select form-select-sm' }) def clean(self): cleaned_data = super().clean() weight = cleaned_data.get('weight', 0) count = cleaned_data.get('count', 0) if weight > 0 and count == 0: self.add_error('count', 'Если указан вес, необходимо указать количество') return cleaned_data class ExcavationForm(forms.ModelForm): """Форма создания/редактирования раскопа""" class Meta: model = Excavation fields = ['name', 'description', 'location', 'start_date', 'end_date'] widgets = { 'start_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), 'end_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), 'description': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'location': forms.TextInput(attrs={'class': 'form-control'}), } class SquareForm(forms.ModelForm): """Форма создания/редактирования квадрата""" class Meta: model = Square fields = ['name', 'size', 'description'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'size': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'например: 2x2 м'}), 'description': forms.Textarea(attrs={'rows': 3, 'class': 'form-control'}), } class PitForm(forms.ModelForm): """Форма создания/редактирования ямы""" class Meta: model = Pit fields = ['name', 'description', 'depth'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'rows': 3, 'class': 'form-control'}), 'depth': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01', 'placeholder': 'глубина в метрах'}), } class LepnayaCeramicsForm(BaseCeramicsForm): class Meta: model = LepnayaCeramics fields = [ 'color_type', 'walls_thin', 'walls_thick', 'rims_simple', 'rims_profiled', 'rims_nail', 'rims_rope', 'bottoms', 'count', 'weight', 'ornament_linear', 'ornament_wave', 'ornament_nail', 'ornament_rope', 'ornament_stamp', 'ornament_combined' ] class EarlyCircularCeramicsForm(BaseCeramicsForm): class Meta: model = EarlyCircularCeramics fields = [ 'color_type', 'walls_thin', 'walls_thick', 'rim_v0', 'rim_v1', 'rim_v2', 'rim_v4', 'rim_vq', 'rim_bowls', 'rim_other', 'bottoms_without', 'bottoms_with', 'stamp', 'count', 'weight', 'ornament_linear', 'ornament_wave', 'ornament_nail', 'ornament_rope', 'ornament_stamp', 'ornament_combined' ] class DevelopedCircularCeramicsForm(BaseCeramicsForm): class Meta: model = DevelopedCircularCeramics fields = [ 'color_type', 'walls_thin', 'walls_thick', 'rim_v0', 'rim_v1', 'rim_v3', 'rim_v4', 'rim_vq', 'rim_bowls', 'rim_other', 'bottoms_without', 'bottoms_with', 'stamp', 'count', 'weight', 'ornament_linear', 'ornament_wave', 'ornament_nail', 'ornament_rope', 'ornament_stamp', 'ornament_combined' ] class LateCircularCeramicsForm(BaseCeramicsForm): class Meta: model = LateCircularCeramics fields = [ 'color_type', 'walls_thin', 'walls_thick', 'rim_v10', 'rim_v11', 'handles', 'bottoms_without', 'bottoms_with', 'stamp', 'count', 'weight', 'ornament_linear', 'ornament_wave', 'ornament_nail', 'ornament_rope', 'ornament_glaze', 'ornament_combined' ] class UndefinedFragmentsForm(BaseCeramicsForm): class Meta: model = UndefinedFragments fields = ['color_type', 'fragment_type', 'count', 'weight'] # Inline formsets LepnayaCeramicsFormSet = inlineformset_factory( Pit, LepnayaCeramics, form=LepnayaCeramicsForm, extra=len(LepnayaCeramics.COLOR_CHOICES), can_delete=True, min_num=0 ) EarlyCircularFormSet = inlineformset_factory( Pit, EarlyCircularCeramics, form=EarlyCircularCeramicsForm, extra=len(EarlyCircularCeramics.COLOR_CHOICES), can_delete=True, min_num=0 ) DevelopedCircularFormSet = inlineformset_factory( Pit, DevelopedCircularCeramics, form=DevelopedCircularCeramicsForm, extra=len(DevelopedCircularCeramics.COLOR_CHOICES), can_delete=True, min_num=0 ) LateCircularFormSet = inlineformset_factory( Pit, LateCircularCeramics, form=LateCircularCeramicsForm, extra=len(LateCircularCeramics.COLOR_CHOICES), can_delete=True, min_num=0 ) UndefinedFragmentsFormSet = inlineformset_factory( Pit, UndefinedFragments, form=UndefinedFragmentsForm, extra=len(UndefinedFragments.FRAGMENT_CHOICES) * 3, can_delete=True, min_num=0 ) # Добавьте эти классы в конец файла forms.py class RegistrationForm(forms.Form): """Форма регистрации""" username = forms.CharField( max_length=150, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Имя пользователя' }) ) email = forms.EmailField( widget=forms.EmailInput(attrs={ 'class': 'form-control', 'placeholder': 'Email' }) ) password = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Пароль' }) ) password_confirm = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Подтверждение пароля' }) ) def clean_username(self): from django.contrib.auth.models import User username = self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): raise forms.ValidationError('Пользователь с таким именем уже существует') return username def clean_email(self): from django.contrib.auth.models import User email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('Пользователь с таким email уже существует') return email def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') password_confirm = cleaned_data.get('password_confirm') if password and password_confirm and password != password_confirm: raise forms.ValidationError('Пароли не совпадают') if password: from django.contrib.auth.password_validation import validate_password try: validate_password(password) except forms.ValidationError as e: raise forms.ValidationError(' '.join(e.messages)) return cleaned_data class ProfileForm(forms.ModelForm): """Форма редактирования профиля""" class Meta: from django.contrib.auth.models import User model = User fields = ['first_name', 'last_name', 'email'] widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), }