Skip to main content
 首页 » 编程设计

python之MyProfile 匹配查询不存在

2025年05月04日35mfryf

事情是这样发生的; 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")