问题
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