5π
I guess you constructed a model that looks similar to:
class UserLocation(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# ...
Contrary to popular belief, a one-to-one field does not mean that the referenced model (here User
) always has a UserLocation
object. A OneToOneField
actually is a ForeignKey
field with a unique=True
constraint (and some extra logic such that the reverse relation is not userlocation_set
, but userlocation
). So it means that two UserLocation
s can never refer to the same User
object.
It is thus possible that there is no user.userlocation
for some user
, and in case the attribute is called, unfortunately it returns not None
, but raises an error (there have been tickets to request that it returns None
, but probably it will not be implemented in the (near) future, because of backwards compatibility).
So you should check with a try
βcatch
βexcept
:
from django.core.exceptions import ObjectDoesNotExist
class Homepage(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super(Homepage, self).get_context_data(**kwargs)
context['event_list'] = Event.objects.all()
if self.request.user.is_authenticated()
try:
my_location = self.request.user.userlocation
except ObjectDoesNotExist:
# ... hande case where the location does not exists
else:
print("The location is {}".format(my_location))
return context
7π
Use an extra condition to your if
clause which checks for an existence of userlocation
attribute by using Pythonβs hasattr()
method
Try this
class Homepage(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super(Homepage, self).get_context_data(**kwargs)
context['event_list'] = Event.objects.all()
if self.request.user.is_authenticated() and \
hasattr(self.request.user, 'userlocation') and \
self.request.user.userlocation:
print("The code reached here ")
return context
Reference
Django check if a related object exists error: RelatedObjectDoesNotExist
- [Django]-How to get a foreignkey object to display full object in django rest framework
- [Django]-Should I use JWT or Sessions for my eCommerce website?
-1π
the User
class doesnβt have userlocation
variable.
use a custom user class inherited from User
- [Django]-Django can't syncdb after drop/create database
- [Django]-Django: "Forbidden (403) CSRF verification failed. Request aborted." in Docker Production
- [Django]-How to put absolute url field in serializer model in django rest framework?
- [Django]-Serializers in django rest framework with dynamic fields