如何提取已登录用户的用户个人资料?詹戈 [英] How do I pull the user profile of the logged in user? django

查看:35
本文介绍了如何提取已登录用户的用户个人资料?詹戈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

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

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

在视图中, request.user 是已登录的用户,所以您可以这样做

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

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

这篇关于如何提取已登录用户的用户个人资料?詹戈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆