DoesNotExist at / Profile matching query does not exist.

Hi, I’m new to Django. I wrote a code that has this error. I tried some solutions but they didn’t work and I need help. sorry if it’s a repetitive question but I can’t find the problem.
this is my view.py file:

@login_required(login_url='signin')
def index(request):
    user_object = User.objects.get(username=request.user.username)
    user_profile = Profile.objects.get(user=user_object)
    return render(request, 'index.html', {'user_profile': user_profile})

this is my model.py:

User = get_user_model()

# Create your models here


class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    id_user = models.IntegerField()
    bio = models.TextField(blank=True)
    profileimg = models.ImageField(upload_to='profile_images', default='blank-profile-picture.png')
    location = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.user.username


class Post(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    user = models.CharField(max_length=100)
    image = models.ImageField(upload_to='post_images')
    caption = models.TextField()
    created_at = models.DateTimeField(default=datetime.now)
    no_of_likes = models.IntegerField(default=0)

    def __str__(self):

and I get this error:


# DoesNotExist at /

Profile matching query does not exist.

C:\Users\Maedeh\PycharmProjects\social_book\social_book\social_book\core\views.py, line 14, in index

        user_profile = Profile.objects.get(user=user_object)

When posting code here, please wrap it with the code tag, using (CTRL + E or CMD + E).
You can edit your post, and do this change.

1 Like

The error is exactly as the message is telling you.

You’re trying to retrieve an instance of Profile where that Profile is referencing a specific user - but no such Profile instance exists.

1 Like

I know the problem. but can’t find a way to retrieve an instance of Profile. it happens when I’m not logged in and it’s on the default user (admin). when I sign in as another user the code work properly.

When you’re not logged in, then there is no profile instance. (AnonymousUser is not a User.)

If you’re logged in as admin, then it’s saying you don’t have an instance of Profile for admin.

maedeh is the admin, and when I sign in as admin it gives the same error.
it’s the first page of the site, so why it’s admin and not AnonymousUser?

I’ve already explained why you’re getting that message. You don’t have an instance of Profile for admin.

thanks but can you explain why it’s admin and not AnonymousUser?

Because you are logged in.

no I didn’t, it’s the first page

That doesn’t matter.

You have an active session with the server. You are logged in.

so when it’s the AnonymousUser?
when i don’t have the @login_required(login_url='signin')?

When you’re not logged in. When you don’t have an active session with the server.

See:

thank you for your time.