Mar*_*chi 2 django django-templates django-views python-3.x
我有下面的代码if self.request.user.is_authenticated() and self.request.user. userlocation我不明白的是为什么我得到这个用户没有用户定位错误。如果他的条件不满足,我有一个 if 语句,如果它不只是下降并显示上下文
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 self.request.user.userlocation:
print("The code reached here ")
return context
Run Code Online (Sandbox Code Playgroud)
下面是models.py
class UserLocation(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
lat = models.FloatField(blank=True, null=True)
lon = models.FloatField(blank=True, null=True)
point = models.PointField(srid=4326, default='SRID=4326;POINT(0.0 0.0)')
objects = models.GeoManager()
Run Code Online (Sandbox Code Playgroud)
对您的if子句使用额外的条件,该条件userlocation通过使用 Python 的hasattr()方法检查属性是否存在
尝试这个
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 contextRun Code Online (Sandbox Code Playgroud)
参考
Django 检查是否存在相关对象错误:RelatedObjectDoesNotExist
我猜您构建了一个类似于以下内容的模型:
class UserLocation(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# ...Run Code Online (Sandbox Code Playgroud)
流行的看法相反,一个对一个领域确实不是意味着参考模型(在这里User),总是有一个UserLocation对象。AOneToOneField实际上是一个ForeignKey具有unique=True约束的字段(以及一些额外的逻辑,使得反向关系不是userlocation_set, but userlocation)。所以这意味着两个UserLocations永远不能引用同一个 User对象。
因此,有可能没有user.userlocationfor some user,并且在调用该属性的情况下,不幸的是它返回not None,但会引发错误(已经有票要求它返回None,但可能不会在(附近)中实现) 未来,因为向后兼容)。
所以你应该检查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 contextRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4694 次 |
| 最近记录: |