Django用户模型后保存破坏单元测试登录



这个信号似乎破坏了我的登录单元测试。我不知道为什么?

信号

@receiver(post_save, sender=User)
def update_profile(sender, instance, **kwargs):
    post_save.disconnect(update_profile, sender=User)
    if Profile.objects.filter(user=instance).exists():
        profile = Profile.objects.get(user=instance)
        if instance.first_name:
            profile.first_name = instance.first_name
        if instance.last_name:
            profile.last_name = instance.last_name
        if instance.email:
            profile.email = instance.email
        profile.save()
        post_save.connect(update_profile, sender=User)
post_save.connect(update_profile, sender=User)

单元测试

class AdminProfileUpdate(TestCase):
    def setUp(self):
        self.user = create_user(password='foobar')
        self.profile = self.user.get_or_create_profile
        self.client = Client()
    def test_profile_base_template(self)
        logged_in = self.client.login(username=self.user.username,
                password='foobar')
        self.assertTrue(logged_in)

在保存后处理程序中调用save()对我来说确实是一个不幸的解决方案。您是否尝试重写save?像这样:

class MyModel(models.Model):
    ...
    def save(self, *args, **kwargs):
        # do the instance changes you want to be saved as well
        super(MyModel, self).save(*args, **kwargs) # do the save operation
        # update anything else, if you want to

最新更新