Django,使用try和except确认

4xy9mtcn  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(82)

我遇到了一个功能错误,需要确认用户是否在那里。下面是www.example.com中的代码views.py:
进口:

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User

字符串
视图:

def (enclosed)View(request, creator_username):
    try:
        creator = get_object_or_404(User, username=creator_username)
    except User.DoesNotExist:
        messages.error(request, "Creator not found.")
        return redirect("homepage")  # Redirect to some error page or homepage


错误:

Class 'User' has no 'DoesNotExist' member


我已经尝试添加“get_object_or_404”,但它仍然不工作。我不知道还有什么办法能让它工作。

vawmfj5a

vawmfj5a1#

问题是函数get_object_or_404()没有返回这个错误,它返回Http404或ValueError
在这种情况下,你可以做的是:

from django.http.response import Http404 # Importing the required error it raises
def (enclosed)View(request, creator_username):
    try:
        creator = get_object_or_404(User, username=creator_username)
    except (ValueError, Http404): # Checking if any of the two are sent back
        messages.error(request, "Creator not found.")
        return redirect("homepage")  # Redirect to some error page or homepage

字符串
该函数的文档参考中,有一个注解,说明它返回一个Http404对象,而不是DoesNotExists

相关问题