当对象DoesNotExist时DetailView重定向(DetailView redirect when object DoesNotExist)

编程入门 行业动态 更新时间:2024-10-15 18:29:44
当对象DoesNotExist时DetailView重定向(DetailView redirect when object DoesNotExist)

我已经开始致力于转换一些使用基于功能的视图的旧代码,以尝试在适用的情况下使用基于类的视图。 我有下面的类,根据一组参数获取配置文件对象。 我的问题是,如果我得到一个DoesNotExist错误,我想重定向到我的应用程序中的特定网址。 我会怎么做呢?

class ProfileView(generic.DetailView): model = Profile template_name = 'area51/profile.html' def get_object(self, queryset=None): return Profile.objects.get(**self.kwargs)

I have started working on converting some old code that uses function based views to try to use class based views where applicable. I have the below class that grabs a profile object based on a set of parameters. My questions is if I get a DoesNotExist error I want to redirect to a specific url in my application. How would I go about that?

class ProfileView(generic.DetailView): model = Profile template_name = 'area51/profile.html' def get_object(self, queryset=None): return Profile.objects.get(**self.kwargs)

最满意答案

你可以重写get方法。 抓住Http404并重定向到所需的URL。

from django.shortcuts import redirect, get_object_or_404 class ProfileView(generic.DetailView): model = Profile template_name = 'area51/profile.html' def get(self, request, *args, **kwargs): try: return super(ProfileView, self).get(request, *args, **kwargs) except Http404: return redirect('/profile-does-not-exist/') def get_object(self, queryset=None): return get_object_or_404(Profile, **self.kwargs)

请注意,我使用了get_object_or_404 ,它将引发Http404而不是DoesNotExist错误。 这与DetailView.get_object方法一致。

You could override the get method. Catch the Http404 and redirect to the required URL.

from django.shortcuts import redirect, get_object_or_404 from django.http import Http404 class ProfileView(generic.DetailView): model = Profile template_name = 'area51/profile.html' def get(self, request, *args, **kwargs): try: return super(ProfileView, self).get(request, *args, **kwargs) except Http404: return redirect('/profile-does-not-exist/') def get_object(self, queryset=None): return get_object_or_404(Profile, **self.kwargs)

Note that I've used get_object_or_404 which will raise Http404 instead of DoesNotExist error. This is to be consistent with the DetailView.get_object method.

更多推荐

本文发布于:2023-08-01 06:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1354916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   对象   DoesNotExist   DetailView   redirect

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!