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

强颜欢笑 提交于 2021-01-28 02:12:42

问题


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.


回答1:


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')



回答2:


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


来源:https://stackoverflow.com/questions/36083945/how-do-i-pull-the-user-profile-of-the-logged-in-user-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!