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_n
Solution 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')
Solution 2:
You have set related_name='profile'
. So you can do:
defhas_profile(user):
try:
return user.profile isnotNoneexcept UserProfile.DoesNotExist:
returnFalse
As a generic way to check if a model has a related, you can do:
from django.core.exceptions import ObjectDoesNotExist
defhas_related(obj, field_name):
try:
returngetattr(obj, field_name) isnotNoneexcept ObjectDoesNotExist:
returnFalse
Post a Comment for "How Do I Pull The User Profile Of The Logged In User? Django"