From 466a9d3c24d32db6f134be896961864bc76444f5 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Tue, 4 Apr 2023 22:39:33 +0100 Subject: [PATCH] Add conditions for fields in UserAdminCreationForm --- .../{{cookiecutter.project_slug}}/users/forms.py | 14 ++++++++++++++ .../users/tests/test_forms.py | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/forms.py b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/forms.py index d9a7446bf..1a61726a1 100644 --- a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/forms.py +++ b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/forms.py @@ -2,7 +2,10 @@ from allauth.account.forms import SignupForm from allauth.socialaccount.forms import SignupForm as SocialSignupForm from django.contrib.auth import forms as admin_forms from django.contrib.auth import get_user_model +{%- if cookiecutter.username_type == "email" %} from django.forms import EmailField +{%- endif %} +from django.utils.translation import gettext_lazy as _ User = get_user_model() @@ -10,7 +13,9 @@ User = get_user_model() class UserAdminChangeForm(admin_forms.UserChangeForm): class Meta(admin_forms.UserChangeForm.Meta): model = User + {%- if cookiecutter.username_type == "email" %} field_classes = {"email": EmailField} + {%- endif %} class UserAdminCreationForm(admin_forms.UserCreationForm): @@ -21,8 +26,17 @@ class UserAdminCreationForm(admin_forms.UserCreationForm): class Meta(admin_forms.UserCreationForm.Meta): model = User + {%- if cookiecutter.username_type == "email" %} fields = ("email",) field_classes = {"email": EmailField} + error_messages = { + "username": {"unique": _("This email has already been taken.")} + } + {%- else %} + error_messages = { + "username": {"unique": _("This username has already been taken.")} + } + {%- endif %} class UserSignupForm(SignupForm): diff --git a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_forms.py b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_forms.py index 1bc326bc8..023aad056 100644 --- a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_forms.py +++ b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_forms.py @@ -24,7 +24,7 @@ class TestUserAdminCreationForm: # hence cannot be created. form = UserAdminCreationForm( { - {%- if cookiecutter.username_type == "email" -%} + {%- if cookiecutter.username_type == "email" %} "email": user.email, {%- else %} "username": user.username, @@ -36,7 +36,7 @@ class TestUserAdminCreationForm: assert not form.is_valid() assert len(form.errors) == 1 - {%- if cookiecutter.username_type == "email" -%} + {%- if cookiecutter.username_type == "email" %} assert "email" in form.errors assert form.errors["email"][0] == _("This email has already been taken.") {%- else %}