我正在向我的Django应用添加个人资料,以存储更多用户信息。跟随https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone
但是,在测试时出现错误。我正在使用django.contrib.auth
中的默认用户模型。
models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
@receiver(post_save, sender=get_user_model())
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=get_user_model())
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
tests / test_model.py
from django.test import TestCase
from app.models import Profile
class ProfileModelTests(TestCase):
@classmethod
def setUpTestData(cls):
Profile.objects.create()
def test_can_create_profile(self):
pass
错误
/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
..........E............
======================================================================
ERROR: setUpClass (project-api.polls.tests.test_models.ProfileModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (158, null).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/test/testcases.py", line 1002, in setUpClass
cls.setUpTestData()
File "/Users/user/programming/gatsby/project-api/polls/tests/test_models.py", line 86, in setUpTestData
Profile.objects.create()
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1283, in execute_sql
cursor.execute(sql, params)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (158, null).
----------------------------------------------------------------------
Ran 22 tests in 2.198s
FAILED (errors=1)
Using existing test database for alias 'default'...
System check identified no issues (0 silenced).
Preserving test database for alias 'default'...
答案 0 :(得分:1)
如果用户不存在,则想法是Profile.objects.create(user=instance)
,因为将找不到user_id,因此将引发IntegrityError异常。创建用户时,信号将监听,而不是相反。
在您的测试用例中,Profile.objects.create()
将尝试与不存在的用户创建一对一关系。
答案 1 :(得分:1)
@receiver(post_save, sender=get_user_model())
使用此代码,您正在听User
模型的save方法来创建相关的Profile
条目及时(如果尚无此条目) 。这样,您就可以开始创建新用户,而不必担心每次都要手动创建和链接个人档案。
请注意,反向操作不涉及以下内容:如果要直接创建配置文件条目,则必须将现有的User对象传递给它,否则将获得IntegrityError
解决方案:可取的是,坚持一种创建用户+配置文件对的主要方法;就您而言,只需创建一个用户,然后让信号自动调用配置文件的创建即可。
class ProfileModelTests(TestCase):
@classmethod
def setUpTestData(cls):
get_user_model().objects.create()
def test_profile(self):
profile = get_user_model().objects.last().profile