代码之家  ›  专栏  ›  技术社区  ›  Harry Moreno

测试Django用户配置文件一对一链接

  •  0
  • Harry Moreno  · 技术社区  · 8 年前

    我正在向我的Django应用程序添加一个配置文件,以存储更多用户信息。跟随 https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone

    然而,我得到一个错误时,测试它。我使用的是来自的默认用户模型 django.contrib.auth .

    型号.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()
    

    测试/测试_型号.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'...
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Harry Moreno    8 年前
    @receiver(post_save, sender=get_user_model())
    

    使用这段代码,您将收听 User Profile 进入 来得正是时候 ,如果还没有的话。这样,您就可以继续创建新用户,而不用担心每次手动创建和链接配置文件。

    请注意,没有涉及相反的内容:如果要直接创建概要文件条目,可以 将现有的用户对象传递给它,否则您将得到一个 IntegrityError

    class ProfileModelTests(TestCase):                                                                                        
        @classmethod                                                                                                          
        def setUpTestData(cls):                                                                                               
            get_user_model().objects.create()                                                                                                                                                                                   
    
        def test_profile(self):                                                                                    
            profile = get_user_model().objects.last().profile
    
        2
  •  2
  •   misraX    8 年前

    这个想法是 Profile.objects.create(user=instance) 如果用户还不存在,将引发IntegrityError异常,因为找不到用户id。信号将在创建用户时监听,而不是相反。 在你的测试用例中 Profile.objects.create() 将尝试与不存在的用户创建一对一关系。