在Django 1.5中使用自定义用户模型作为ForeignKey进行测试

时间:2022-10-15 19:22:56

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.

我正在使用Django 1.5,我正在努力使应用程序适用于任何自定义用户模型。我已经将应用程序更改为在任何地方使用get_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:

问题是我希望能够测试应用程序,但我找不到使用自定义用户模型使ForeignKey模型字段正确测试的方法。当我运行下面附带的测试用例时,我收到此错误:

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?

我在这里描述的ForeignKey参数列表中引用了用户模型,但是使用get_user_model并没有改变任何东西,因为在设置更改发生之前评估了用户属性。当我使用自定义用户模型时,有没有办法让这个ForeignKey在测试中发挥出色?

1 个解决方案

#1


3  

I asked about this on the Django mailing list as well but it seems that, at least currently, there is no way to change the settings.AUTH_USER_MODEL and have it work nicely with a ForeignKey.

我也在Django邮件列表上询问过这个问题,但似乎至少目前还没有办法更改settings.AUTH_USER_MODEL,并且可以很好地使用ForeignKey。

So far, in order to test my app, I've created a runtests.py file from this answer:

到目前为止,为了测试我的应用程序,我从这个答案中创建了一个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,
    ...
)

...

And added a bash script to actually run the tests using different user models:

并添加了一个bash脚本来实际使用不同的用户模型运行测试:

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

The last bit is to use a function to actually retrieve the right user model info instead of just using a "static" variable:

最后一点是使用函数来实际检索正确的用户模型信息,而不是仅仅使用“静态”变量:

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

I'm not claiming this to be a correct answer for the problem, but so far... It works.

我并没有声称这是对这个问题的正确答案,但到目前为止......它的确有效。

#1


3  

I asked about this on the Django mailing list as well but it seems that, at least currently, there is no way to change the settings.AUTH_USER_MODEL and have it work nicely with a ForeignKey.

我也在Django邮件列表上询问过这个问题,但似乎至少目前还没有办法更改settings.AUTH_USER_MODEL,并且可以很好地使用ForeignKey。

So far, in order to test my app, I've created a runtests.py file from this answer:

到目前为止,为了测试我的应用程序,我从这个答案中创建了一个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,
    ...
)

...

And added a bash script to actually run the tests using different user models:

并添加了一个bash脚本来实际使用不同的用户模型运行测试:

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

The last bit is to use a function to actually retrieve the right user model info instead of just using a "static" variable:

最后一点是使用函数来实际检索正确的用户模型信息,而不是仅仅使用“静态”变量:

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

I'm not claiming this to be a correct answer for the problem, but so far... It works.

我并没有声称这是对这个问题的正确答案,但到目前为止......它的确有效。