-2

I'm building a Django server for my company and I'm still unfamiliar with some processes. I'm sure this is super simple, I'm just completely unaware of how this works.

How do I differentiate between user's data so it doesn't get mixed up?

If Jill is a user and she requests a page of her profile data, how do I not send her Jack's profile data, especially if there are multiple models invovled?

For example, the code in the view would look like this:

def display_profile(request)
    profile = Profile.objects.get(???) # What do I put in here?

I understand that I can do:

def display_profile(request, user)
    profile = Profile.objects.get(user_id=user)

But that's not my design intention.

Thank you in advance.

grantjay
  • 100
  • 6
  • _"that's not my design intention"_: What is your design intention? What is wrong with that approach? – Selcuk Jan 07 '21 at 03:26
  • https://docs.djangoproject.com/en/3.1/topics/auth/default/#authentication-in-web-requests – iklinac Jan 07 '21 at 03:34

2 Answers2

1

In your Django view, you can access the current user with request.user.

So if you want to get a Profile instance matching your current logged in user, just do a query as follow:

profile = Profile.objects.get(user=request.user)

This assumes you have a user foreign key field (or OneToOne) in your Profile model.

Guillaume
  • 1,956
  • 1
  • 7
  • 9
1

As documented

Django uses sessions and middleware to hook the authentication system into request objects.

These provide a request.user attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User.

So in your case (notice field not being called user_id )

profile = Profile.objects.get(user=user)
iklinac
  • 14,944
  • 4
  • 28
  • 30