﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34438	UserCreationForm.clean_username() crashes with a custom user model.	Gary Jarrel	Gary Jarrel	"Our project users a custom user model defined in settings via {{{AUTH_USER_MODEL}}}

There is a basic test case:
{{{#!python
def test_username_validation_error_msg(self, user: User):
	# The user already exists,
	# hence cannot be created.
	form = UserAdminCreationForm(
	    {
	        ""username"": user.username,
	        ""password1"": user.password,
	        ""password2"": user.password,
	    }
	)

	assert not form.is_valid()
	assert len(form.errors) == 1
	assert ""username"" in form.errors
	assert form.errors[""username""][0] == _(""This username has already been taken."")
}}}

This works in Django 4.1, however when I ran the test suite against 4.2rc1 and the current main branch, I get failures. 

{{{
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'
}}}

with the trace 

{{{
../../contrib/django/django/forms/forms.py:197: in is_valid
    return self.is_bound and not self.errors
../../contrib/django/django/forms/forms.py:192: in errors
    self.full_clean()
../../contrib/django/django/forms/forms.py:327: in full_clean
    self._clean_fields()
../../contrib/django/django/forms/forms.py:342: in _clean_fields
    value = getattr(self, ""clean_%s"" % name)()
../../contrib/django/django/contrib/auth/forms.py:158: in clean_username
    if username and User.objects.filter(username__iexact=username).exists():
}}}

I believe it relates to this [[https://github.com/django/django/commit/298d02a77a69321af8c0023df3250663e9d1362d | commit]]

The line 
{{{
#!python
if username and User.objects.filter(username__iexact=username).exists()
}}}

When I changed the line to: 

{{{
#!python
if username and UserModel.objects.filter(username__iexact=username).exists()
}}}

The error was resolved.

This could potentially be related to: [https://code.djangoproject.com/ticket/28608 28608], but it seems like a very old ticket, when compared to the [[https://github.com/django/django/commit/298d02a77a69321af8c0023df3250663e9d1362d | commit]] which was done in December 22

''As a side note, the test then failed due to the change in the error message from:''

{{{
""This username has already been taken.""
}}}

to 
{{{
A user with that username already exists.
}}}

But that's not a big issue. "	Bug	closed	contrib.auth	4.2	Release blocker	fixed		gary@… Paul Schilling	Ready for checkin	1	0	0	0	0	0
