"UserProfile matching query does not exist" error, however, I'm trying to create one

450 views Asked by At

I have UserProfile corresponded to User model in Django 1.8, I want when a user logs in, it creates one UserProfile automatically, But I encounter with following error:

UserProfile matching query does not exist.

In main Project View:

def get_or_create_user_profile(request):
    user = request.user
    try:
        profile = user.userprofile
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user=user)
    return profile

My UserProfile Model

def get_image_path(instance, filename):
    formats = str(instance.id) + 'moolak' + '.' + filename.split('.')[-1]
    return os.path.join('../media/images/users/', str(instance.id)+'/avatar', formats)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(blank=True, upload_to=get_image_path, default='/static/image/avatar/male.png')
    age = models.IntegerField(blank=True, validators=[MinValueValidator(3), MaxValueValidator(99)])

def save(self, *args, **kwargs):
    this = UserProfile.objects.get(id=self.id)
    if this.avatar != self.avatar:
        this.avatar.delete(save=False)
    super(UserProfile, self).save(*args, **kwargs)
0

There are 0 answers