siteforglod/club/forms.py
2026-02-16 14:05:26 +03:00

62 lines
2.1 KiB
Python

from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from .models import Profile
class BootstrapMixin:
"""Add Bootstrap classes to form fields."""
def _init_bootstrap(self):
for name, field in self.fields.items():
existing_classes = field.widget.attrs.get("class", "")
field.widget.attrs["class"] = f"form-control {existing_classes}".strip()
class RegistrationForm(BootstrapMixin, UserCreationForm):
first_name = forms.CharField(label="Имя", max_length=150)
last_name = forms.CharField(label="Фамилия", max_length=150)
phone = forms.CharField(label="Телефон", max_length=20)
email = forms.EmailField(label="Email", required=False)
class Meta:
model = User
fields = (
"username",
"first_name",
"last_name",
"phone",
"email",
"password1",
"password2",
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._init_bootstrap()
self.fields["username"].label = "Логин"
for name in ["password1", "password2"]:
self.fields[name].widget.attrs["autocomplete"] = "new-password"
def save(self, commit=True):
user = super().save(commit=False)
user.first_name = self.cleaned_data.get("first_name", "")
user.last_name = self.cleaned_data.get("last_name", "")
user.email = self.cleaned_data.get("email", "")
if commit:
user.save()
Profile.objects.update_or_create(
user=user, defaults={"phone": self.cleaned_data.get("phone", "")}
)
return user
class LoginForm(BootstrapMixin, AuthenticationForm):
username = forms.CharField(label="Логин")
password = forms.CharField(label="Пароль", widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._init_bootstrap()
self.fields["username"].widget.attrs["autofocus"] = True