Django - UserProfile m2m field in admin - error

后端 未结 1 1900
无人共我
无人共我 2020-12-30 11:17

My models:

class UserProfile(models.Model):
    TYPES_CHOICES = (
        (0, _(u\'teacher\')),
        (1, _(u\'student\')),
    )
    user = models.Foreign         


        
相关标签:
1条回答
  • 2020-12-30 11:35

    I had this same issue recently. It actually makes perfect sense when you think about it. When you save a form with inlines in the admin, it saves the main model first, and then proceeds to save each inline. When it saves the model, your post_save signal is fired off and a UserProfile is created to match, but now it's time to save the inlines. The UserProfile inline is considered new, because it didn't exist previously (has no pk value), so it tries to save as an entirely new and different UserProfile and you get that integrity error for violating the unique constraint. The solution is simple. Just override UserProfile.save:

    def save(self, *args, **kwargs):
        if not self.pk:
            try:
                p = UserProfile.objects.get(user=self.user)
                self.pk = p.pk
            except UserProfile.DoesNotExist:
                pass
    
        super(UserProfile, self).save(*args, **kwargs)
    

    Essentially, this just checks if there's an existing UserProfile for the user in question. If so, it sets this UserProfile's pk to that one's so that Django does an update instead of a create.

    0 讨论(0)
提交回复
热议问题