Search code examples
pythondjangodjango-users

Get a related profile via request.user in django 1.8+


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?


Solution

  • 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