RelatedObjectDoesNotExist: User has no userprofile

后端 未结 7 1086
旧巷少年郎
旧巷少年郎 2020-12-28 17:58

So I\'ve extended my user with the field score like this:

models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(Us         


        
7条回答
  •  佛祖请我去吃肉
    2020-12-28 18:41

    Nothing in what you've done forces the creation of a UserProfile object when a User is created. There are two basic ways of handling this:

    1. If you always want a UserProfile to exist (which seems like the case as you give a default value to score, create a post_save handler that creates a new profile when ever the User object is created (but not every time it's saved, so make sure to check the created argument in the handler).

    2. If it's expected a user may not have a profile, you need to catch the UserProfile.DoesNotExist exception when trying to access it. If you do this frequently, make some kind of helper function.

    UPDATED TO ANSWER SIGNAL QUESTION

    It also looks like somewhere around here post_save.connect(create_profile, sender=User) should be added?

    You would need to define a function called create_profile and then wire it up as you have shown. I typically do this right in the models.py file that includes the sender but in this case where the sender is a built-in Django model and you're already importing that model into the file where you define your UserProfile that's the place to do it. It would look something like:

    def create_profile(sender, instance, created, *args, **kwargs):
        # ignore if this is an existing User
        if not created:
            return
        UserProfile.objects.create(user=instance)
    post_save.connect(create_profile, sender=User)
    

提交回复
热议问题