I'm using Django 1.5 and I'm trying to make an application work with any custom user model. I've changed the app to use get_user_model
everywhere and the app itself is not showing any problems so far.
The issue is that I want to be able to test the app as well, but I can't find a way to make ForeignKey
model fields to test correctly using custom user models. When I run the test case attached below, I get this error:
ValueError: Cannot assign "<NewCustomUser: alice@bob.net>": "ModelWithForeign.user" must be a "User" instance.
This is the file I'm using for testing:
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.tests.custom_user import CustomUser, CustomUserManager
from django.db import models
from django.test import TestCase
from django.test.utils import override_settings
class NewCustomUser(CustomUser):
objects = CustomUserManager()
class Meta:
app_label = 'myapp'
class ModelWithForeign(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
@override_settings(
AUTH_USER_MODEL = 'myapp.NewCustomUser'
)
class MyTest(TestCase):
user_info = {
'email': 'alice@bob.net',
'date_of_birth': '2013-03-12',
'password': 'password1'
}
def test_failing(self):
u = get_user_model()(**self.user_info)
m = ModelWithForeign(user=u)
m.save()
I'm referencing the user model in the ForeignKey
argument list as described here, but using get_user_model
there doesn't change anything, as the user
attribute is evaluated before the setting change takes place. Is there a way to make this ForeignKey play nice with testing when I'm using custom user models?