gpt4 book ai didi

python - MyProfile 匹配查询不存在

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:53 25 4
gpt4 key购买 nike

事情是这样发生的;DoesNotExist 在/post/naver/

我现在收到这个错误,因为我在这一行的末尾添加了 id,profile = MyProfile.objects.get(user=request.user.id)
我正在使用 userena。我必须使用 id,否则它不会给出 'SimpleLazyObject'

这是回溯

Traceback:
/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
/ebagu/main/views.py" in post
87. profile = MyProfile.objects.get(user=request.user.id)
/env/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
127. return getattr(self.get_queryset(), name)(*args, **kwargs)
/env/local/lib/python2.7/site-packages/django/db/models/query.py" in get
334. self.model._meta.object_name

Exception Type: DoesNotExist at /post/naver/
Exception Value: MyProfile matching query does not exist.

最佳答案

如果不能保证配置文件存在于数据库中,您将需要编写代码来处理这种情况。一种常见的方法是捕获 DoesNotExist 异常。

try:
profile = MyProfile.objects.get(user=request.user)
# if it's a OneToOne field, you can do:
# profile = request.user.myprofile
except MyProfile.DoesNotExist:
profile = None
# other code that handles missing profile

如果所有登录用户都有一个配置文件,但您的 View 也在处理匿名用户,那么如果您改用 if 语句,您的代码可能会更清晰。您可以实例化一个显示匿名用户默认值的配置文件。

if request.user.is_authenticated():
profile = request.user.myprofile
else:
profile = MyProfile(favourite_food="pasta", favourite_colour="blue")

关于python - MyProfile 匹配查询不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35428257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com