Reputation: 746
I've swapped the User
model with my own custom User
model. It uses the standard UserManager
. I also have a CustomUserChangeForm
which is used in my UserAdmin
. I've set AUTH_USER_MODEL = "accounts.User"
in settings.
This all works fine when using the site and admin site normally through the browser. Tests on my views that use the custom User
model also work fine.
Only when I try to run a test directly on the CustomUserChangeForm
I get the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
.
What's going wrong here?
The test:
from .forms import CustomUserChangeForm
from .models import User
def test_admin_user_change_form(self):
self.register_user()
self.register_user("[email protected]", "username2")
user = User.objects.get(username="username")
# Test valid change
form = CustomUserChangeForm({ "username": "username3", "email": "[email protected]" }, user)
self.assertTrue(form.is_valid())
# Test case insensitive username change
form = CustomUserChangeForm({ "username": "Username2" }, user)
self.assertFalse(form.is_valid())
# Test case insensitive email change
form = CustomUserChangeForm({ "email": "[email protected]" }, user)
self.assertFalse(form.is_valid())
The form:
from .models import User
class CustomUserChangeForm(UserChangeForm):
def clean_username(self):
username = self.cleaned_data.get("username")
if username and self._meta.model.objects.exclude(id=self.instance.id).filter(username__iexact=username).exists():
self._update_errors(ValidationError({ "username": self.instance.unique_error_message(self._meta.model, ["username"]) }))
else:
return username
def clean_email(self):
return self.cleaned_data.get("email").lower()
Admin:
from django.contrib.auth.admin import UserAdmin
from .models import User
@admin.register(User)
class UserAdmin(UserAdmin):
# ...
form = CustomUserChangeForm
# ...
The answers at this question and this question do not seem to apply/work.
Not sure why this was closed. The linked question is different in that everything is working fine during normal use. Only in the automated test am I getting an error. None of the answers provided in that question solve my problem.
Upvotes: 1
Views: 34