我已经开始致力于转换一些使用基于功能的视图的旧代码,以尝试在适用的情况下使用基于类的视图。 我有下面的类,根据一组参数获取配置文件对象。 我的问题是,如果我得到一个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.
更多推荐
发布评论