我正在尝试在django rest框架测试用例中创建一个新用户,以便能够使用以下代码创建发布操作:
from django.contrib.auth.models import User
user = User.objects.create_user('username', 'Pas$w0rd')
user = authenticate(username='username', password='Pas$w0rd')
client = APIClient()
client.force_authenticate(user=user)
r = client.post('/api/v1/event/', {'name': 'testevent'}, format='json')
出现以下错误:
user = User.objects.create_user('username', 'Pas$w0rd')
File "/opt/dev/wgptx/venv/lib/python2.7/site-packages/django/db/models/manager.py", line 277, in __get__
self.model._meta.swapped,
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'account.User'
请帮忙吗?
答案 0 :(得分:2)
错误似乎是您在使用扩展的用户模型。
,因此您应该使用
from account.models import User
因此,您的测试模块就像
from account.models import User
user = User.objects.create_user('username', 'Pas$w0rd')
user = authenticate(username='username', password='Pas$w0rd')
client = APIClient()
client.force_authenticate(user=user)
r = client.post('/api/v1/event/', {'name': 'testevent'}, format='json')
或
将get_user_model
函数用作
from django.contrib.auth import get_user_model
User = get_user_model()
user = User.objects.create_user('username', 'Pas$w0rd')
user = authenticate(username='username', password='Pas$w0rd')
client = APIClient()
client.force_authenticate(user=user)
r = client.post('/api/v1/event/', {'name': 'testevent'}, format='json')