43Tesseracts 43Tesseracts - 10 months ago 33
Python Question

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:

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:


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

However if I:
the result is

I also confirmed that the users actually have profiles.

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


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