56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
from secrets import token_hex
|
|
|
|
from django import forms
|
|
from django.contrib.auth import forms as auth_forms
|
|
from django.db import transaction
|
|
|
|
from .models import Membre, User
|
|
|
|
|
|
class BootstrapMixin:
|
|
required_css_class = "required"
|
|
|
|
widget_classes = {
|
|
"checkbox": "form-check-input",
|
|
"select": "form-select",
|
|
}
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
for field in self.fields.values():
|
|
if getattr(field.widget, "_bs_enabled", False):
|
|
continue
|
|
widgets = getattr(field.widget, "widgets", [field.widget])
|
|
for widget in widgets:
|
|
input_type = getattr(widget, "input_type", "")
|
|
class_name = self.widget_classes.get(input_type, "form-control")
|
|
if "class" in widget.attrs:
|
|
widget.attrs["class"] += " " + class_name
|
|
else:
|
|
widget.attrs.update({"class": class_name})
|
|
|
|
|
|
class LoginForm(BootstrapMixin, auth_forms.AuthenticationForm):
|
|
username = forms.EmailField(
|
|
widget=forms.EmailInput(attrs={"autofocus": True}),
|
|
)
|
|
|
|
|
|
class UserEditForm(BootstrapMixin, forms.ModelForm):
|
|
class Meta:
|
|
model = Membre
|
|
fields = [
|
|
"nom", "prenom", "fonction", "rue", "npa", "localite",
|
|
"tel1", "tel2", "courriel", "date_naissance", "annee_entree",
|
|
]
|
|
|
|
@transaction.atomic()
|
|
def save(self, **kwargs):
|
|
is_new = self.instance.pk is None
|
|
if is_new:
|
|
self.instance.user = User.objects.create_user("foo", self.instance.courriel, password=token_hex(10))
|
|
elif "courriel" in self.changed_data:
|
|
self.instance.user.email = self.cleaned_data["courriel"]
|
|
self.instance.user.save()
|
|
return super().save(**kwargs)
|