Testing with a custom model as ForeignKey in Django 1.5

I am using Django 1.5 and I am trying to make the application work with any custom model. I changed the application to use get_user_modeleverywhere, and the application itself does not yet show any problems.

The problem is that I also want to test the application, but I can’t find a way to make the model fields ForeignKeyvalidated correctly using user user models. When I run the test case below, I get this error:

ValueError: Cannot assign "<NewCustomUser: alice@bob.net>": "ModelWithForeign.user" must be a "User" instance.

This is the file I use 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()

ForeignKey, , get_user_model , user . ForeignKey , ?

+5
1

Django, , , , settings.AUTH_USER_MODEL ForeignKey.

, , runtests.py :

import os, sys
from django.conf import settings

if len(sys.argv) >= 2:
    user_model = sys.argv[1]
else:
    user_model = 'auth.User'

settings.configure(
    ...
    AUTH_USER_MODEL=user_model,
    ...
)

...

bash script :

for i in "auth.User" "myapp.NewCustomUser"; do
    echo "Running with AUTH_USER_MODEL=$i"
    python runtests.py $i
    if [ $? -ne 0 ]; then
        break
    fi
done

, , "" :

def get_user_info():
    if settings.AUTH_USER_MODEL == 'auth.User':
        return {default user info}
    if settings.AUTH_USER_MODEL == 'myapp.NewCustomUser':
        return {my custom user info}
    raise NotImplementedError

, , ... .

+3

All Articles