#35578: Customizing `username_validator` in custom User model extending
`django.contrib.auth.models.AbstractUser` doesn't work
------------------------------+-----------------------------------------
     Reporter:  Oscar Rovira  |                     Type:  Uncategorized
       Status:  new           |                Component:  contrib.auth
      Version:  5.0           |                 Severity:  Normal
     Keywords:                |             Triage Stage:  Unreviewed
    Has patch:  0             |      Needs documentation:  0
  Needs tests:  0             |  Patch needs improvement:  0
Easy pickings:  0             |                    UI/UX:  0
------------------------------+-----------------------------------------
 Hi there!
 I'm sorry if that is the expected behaviour of what I'm going to report,
 but looking at the implementation, it should work as I expected.
 I have my own authentication `User` model, extending from `AbstracUser`.
 Looking at the code of `AbstractUser`, one may think that defining the
 class prop `username_validator`, the validation of the username at all the
 levels (createsuperuser command, Admin create user form,
 User.objects.create_user, ...) should use the new validator provided in
 the customized class. It is not working like that. In order to make it
 work, one has to re-define also the `username` field in the customized
 model.

 So, I have the following:
 {{{
 @deconstructible
 class CustomUnicodeUsernameValidator(validators.RegexValidator):
     """Overrides the default username validator from Django Abstract
     User to avoid usernames with characters '@', '+' or '.'
     """
     regex = r"^[\w-]+\Z"
     message = _(
         "Enter a valid username. This value may contain only letters, "
         "numbers, and -/_ characters."
     )
     flags = 0

 ...
 class User(AbstractUser):
     """Main app user, extending default Django users."""

     # overriding the one defined in AbstractUser
     username_validator = CustomUnicodeUsernameValidator() # type: ignore

     # Other custom fields
     ...
 }}}

 and it does not work, the custom username_validator is not being used.

 However, if I redefine the `username` field, including the
 `validators=[username_validator]` attribute, it works as expected.
 As I said, maybe it is the expected behaviour, and it's just a lack of
 documentation.

 Thanks!
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35578>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/01070190837b5cb8-d7b714c6-bc56-44a6-b147-9c1eb4e7ed02-000000%40eu-central-1.amazonses.com.

Reply via email to