繁体   English   中英

如何提取已登录用户的用户个人资料? Django的

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

我正在使用Django的内置用户模型和此UserProfile模型。

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

如何检查登录用户是否具有关联的用户配置文件,并在context_dict中传递bool值?

我需要决定在主页上显示“创建配置文件”还是“编辑配置文件”。 谢谢。

如果不需要获取配置文件,则可以使用hasattr ,并避免进行异常处理。

user_has_profile = hasattr(user,  'profile')

在视图中, request.user是登录用户,因此您可以

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

您已设置related_name='profile' 因此,您可以执行以下操作:

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

作为检查模型是否相关的一种通用方法,您可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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