简体   繁体   中英

How do I pull the user profile of the logged in user? django

I'm using Django's built in User model and this UserProfile model.

# this is model for user profile
class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    city = models.ForeignKey(City)
   .
   .
   .
   general attributes

How can I check if the logged in user has an associated user profile and pass the bool value in the context_dict?

I need that to decide whether to show "Create Profile" or "Edit Profile" in the homepage. Thank you.

If you do not need to fetch the profile, you can use hasattr , and avoid the need for exception handling.

user_has_profile = hasattr(user,  'profile')

In a view, request.user is the logged in user so you would do

user_has_profile = hasattr(request.user,  'profile')

You have set related_name='profile' . So you can do:

def has_profile(user):
    try:
        return user.profile is not None
    except UserProfile.DoesNotExist:
        return False

As a generic way to check if a model has a related, you can do:

from django.core.exceptions import ObjectDoesNotExist

def has_related(obj, field_name):
    try:
        return getattr(obj, field_name) is not None
    except ObjectDoesNotExist:
        return False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM