Wednesday, March 13, 2013

Testing with a custom user model as a ForeignKey in Django 1.5

I'm using Django 1.5 and I'm trying to make an application work with
any custom user model.

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 in https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.get_user_model,
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?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment