How to redirect on conditions with class based views in Django 1.3?

时光总嘲笑我的痴心妄想 提交于 2019-12-03 10:40:26

问题


I am using a ListView that list videos according to tags. The filtering happens in get_queryset(). I'd like to redirect the user to another page if the tag doesn't contains any video.

With a function, it would be easy. Query, check the queryset, redirect. With a class, I fail doing so:

class VideosView(generic.ListView):

    def get_queryset(self):
        """
            This work.
        """

        tag = self.kwargs.get('tag', None)

        self.videos = Video.on_site.all()

        if tag:
            self.videos = Video.tagged.with_all(tag, self.videos)

        return self.videos

    def get(self, request, *args, **kwargs):
        """
        This doesn't work because self.videos doesn't exist yet.
        """
        if not self.videos:
            return redirect('other_page')

        return super(Videos, self).get(request, *args, **kwargs)

回答1:


I know this is old, but I actually agree with Tommaso. The dispatch() method is what handles the request and returns the HTTP response. If you want to adjust the response of the view, thats the place to do it. Here are the docs on dispatch().

class VideosView(ListView):
    # use model manager
    queryset = Videos.on_site.all()

    def dispatch(self, request, *args, **kwargs):
        # check if there is some video onsite
        if not queryset:
            return redirect('other_page')
        else:
            return super(VideosView, self).dispatch(request, *args, **kwargs)

    # other method overrides here



回答2:


Found it:

def render_to_response(self, context):

    if not self.videos:
        return redirect('other_page')

    return super(VideosView, self).render_to_response(context)

This is called for all HTTP methods




回答3:


According to django doc :

in url.py

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
     ...
    url(r'^go-to-django/$', RedirectView.as_view(url='http://djangoproject.com'), name='go-to-django'),
..
)


来源:https://stackoverflow.com/questions/5433172/how-to-redirect-on-conditions-with-class-based-views-in-django-1-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!