2012-03-13 18 views
0

这个信号似乎打破了我的单元测试登录。我不知道为什么?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) 
+0

请发布您的**实际**代码。我们需要重现的一切。不要发布有明显错误或者不能编译的代码(例如缺少导入)。 – jpic 2012-03-13 08:10:12

+0

为什么要断开信号然后重新连接?为什么不把它连接起来? (如果配置文件不存在,你为什么要断开信号连接?) – 2012-03-13 09:32:49

+0

啊......这是我的愚蠢。该错误与信号无关。在我的个人资料模型中,我将相同的字段保存到用户模型中,因此出现了一些时髦的递归。我怎样才能关闭这个问题? – super9 2012-03-13 10:47:44

回答

1

在调用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