2

I have a Profile model:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="profile_user")
    preferred_name = models.CharField()
    # more profile fields

that I want to access in a template via the user: {{request.user}}

However previous answers to this question use a method that was removed in 1.7:

"These features have reached the end of their deprecation cycle and so have been removed in Django 1.7:

  • The AUTH_PROFILE_MODULE setting, and the get_profile() method on the User."

The docs now say I should just do this, but it doesn't return anything:

{{request.user.profile.profile_field_i_want}}

the only difference I can see between the example and my profile model is that I use settings.AUTH_USER_MODEL but the example uses User as the OneToOne.

However if I: print(settings.AUTH_USER_MODEL) the result is auth.User

I also confirmed that the users actually have profiles.

How do I access a user's related profile via request.user?

Community
  • 1
  • 1
43Tesseracts
  • 4,617
  • 8
  • 48
  • 94

3 Answers3

8

To access user profile from User model, you need to use related_name that was passed as argument in OneToOneField inside Profile model.

So to call preferred_name you need to do:

{{ request.user.profile_user.preferred_name }}

because you've provided 'profile_user' as related_name

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
3

Your related_name is "profile_user", do you should use that.

{{request.user.profile_user.profile_field_i_want}}

I must say, though, I don't know why you've set that attribute: the default value of *profile" makes much more sense.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks for the critique. I didn't realize what that was for and it must have been vestigial from following a tutorial. – 43Tesseracts Aug 23 '15 at 20:46
2

You can just relate your profile name's id (the model class) with the User model's id like this:

    user = User.objects.get(id=request.user.id)  
    profile = Profile.objects.filter(user=user).get()  
    instance = profile

Then call the profile attributes as so:

    {{ profile.phone_number }}