Back

Explore Courses Blog Tutorials Interview Questions
0 votes
6 views
in Python by (45.3k points)
edited by

Could someone tell me how to get a view that gets the current user profile? I am aware of get_profile, but I don't know how to use it. There is a snippet I found from the Django document that I will share here: 

from django.contrib.auth.models import User

profile=request.user.get_profile()

1 Answer

0 votes
by (16.8k points)
edited by

Django's documentation says it all, specifically the part Storing additional information about users. First you need to define a model somewhere in your models.py with fields for the additional information of the user:

models.py

from django.contrib.auth.models import User

class UserProfile(models.Model):

    # This field is required.

    user = models.OneToOneField(User)

    # Other fields here

    accepted_eula = models.BooleanField()

    favorite_animal = models.CharField(max_length=20, default="Dragons.")

Then, you need to indicate that this model (UserProfile) is the user profile by setting AUTH_PROFILE_MODULE inside your settings.py:

settings.py

...

AUTH_PROFILE_MODULE = 'accounts.UserProfile'

...

You need to replace accounts with the name of your app. Finally, you want to create a profile every time a User instance is created by registering a post_save handler, this way every time you create a user Django will create his profile too:

models.py

from django.contrib.auth.models import User

class UserProfile(models.Model):

    # This field is required.

    user = models.OneToOneField(User)

    # Other fields here

    accepted_eula = models.BooleanField()

    favorite_animal = models.CharField(max_length=20, default="Dragons.")

def create_user_profile(sender, instance, created, **kwargs):

    if created:

UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

Accessing the Profile

To access the current user's profile in your view, just use the User instance provided by the request, and call get_profile on it:

def your_view(request):

    profile = request.user.get_profile()

    ...

    # Your code

by (120 points)
how do I get the profile of another user by clicking their username?

Browse Categories

...