在类视图的get_object方法中,如果if语句失败,我可以将用户定向到模板而不是返回对象吗?
目前,Http404("Some message.")很好用,但是它看起来不太好,我想使用我自己的模板。
我正在尝试这样做,但使用模板:
def get_object(self):
product = Product.objects.get(slug=self.kwargs.get('slug'))
if product.deleted == False:
if product.out_of_stock == False:
return product
else:
raise Http404("This product is sold out.")
# return reverse("404-error", kwargs={"error": "sold-out"})
# return render(request, "custom_404.html", {"error": "sold_out"})
else:
raise Http404("This product is no longer available.")
# return reverse("404-error", kwargs={"error": "deleted"})
# return render(request, "custom_404.html", {"error": "deleted"})我的主要目标是避免获取对象。我知道我可以在get_context_data方法中执行if语句,但是对于包含敏感数据的对象,我不确定用户是否有任何方法在get_object中访问它,所以我只想避免在条件失败时完全获得对象,并向用户显示一个模板。
发布于 2022-04-02 04:19:28
当发生404错误时,您可以使用自己的视图,首先创建一个自定义视图:
视图
from django.shortcuts import render
def handler404(request, *args, **kwargs):
return render(request, template_name='custom_404.html', status=404)现在您需要覆盖默认的404视图,将其添加到主urls.py文件中:
urls.py
handler404 = 'appname.views.handler404' # Replaces appname with the name of the app that contains the custom view现在,您可以简单地引发一个Http404异常来显示您的自定义模板(您可以保留实际代码)。
https://stackoverflow.com/questions/71714655
复制相似问题