|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""API Django admin amendments.""" |
| 3 | +# pylint: disable=imported-auth-user |
| 4 | +from django.contrib import admin |
| 5 | +from django.contrib.auth.admin import UserAdmin |
| 6 | +from django.contrib.auth.forms import UserCreationForm, UserChangeForm |
| 7 | +from django.contrib.auth.models import User |
| 8 | +from django.core.exceptions import ValidationError |
| 9 | + |
| 10 | + |
| 11 | +class BaseCustomUserForm: |
| 12 | + """ |
| 13 | + Base form class for custom user forms. |
| 14 | + Contains common logic for validating the username. |
| 15 | + """ |
| 16 | + |
| 17 | + def clean_username(self): |
| 18 | + """ |
| 19 | + Clean the username field to ensure it does not contain hyphens. |
| 20 | + Raises: |
| 21 | + ValidationError: If the username contains hyphens. |
| 22 | + Returns: |
| 23 | + str: The cleaned username. |
| 24 | + """ |
| 25 | + username = self.cleaned_data["username"] |
| 26 | + if "-" in username: |
| 27 | + raise ValidationError("Usernames cannot contain hyphens.") |
| 28 | + return username |
| 29 | + |
| 30 | + |
| 31 | +class CustomUserCreationForm(BaseCustomUserForm, UserCreationForm): |
| 32 | + """ |
| 33 | + Custom form for user creation. |
| 34 | + Inherits from BaseCustomUserForm and UserCreationForm. |
| 35 | + """ |
| 36 | + |
| 37 | + class Meta(UserCreationForm.Meta): |
| 38 | + model = User |
| 39 | + |
| 40 | + |
| 41 | +class CustomUserChangeForm(BaseCustomUserForm, UserChangeForm): |
| 42 | + """ |
| 43 | + Custom form for user change. |
| 44 | + Inherits from BaseCustomUserForm and UserChangeForm. |
| 45 | + """ |
| 46 | + |
| 47 | + class Meta(UserChangeForm.Meta): |
| 48 | + model = User |
| 49 | + |
| 50 | + |
| 51 | +class CustomUserAdmin(UserAdmin): |
| 52 | + """ |
| 53 | + Custom User admin panel configuration. |
| 54 | + """ |
| 55 | + |
| 56 | + add_form = CustomUserCreationForm |
| 57 | + form = CustomUserChangeForm |
| 58 | + |
| 59 | + |
| 60 | +admin.site.unregister(User) |
| 61 | +admin.site.register(User, CustomUserAdmin) |
0 commit comments