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

后端 未结 3 974
梦毁少年i
梦毁少年i 2021-02-05 03:02

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 an

相关标签:
3条回答
  • 2021-02-05 03:32

    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
    
    0 讨论(0)
  • 2021-02-05 03:33

    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'),
    ..
    )
    
    0 讨论(0)
  • 2021-02-05 03:35

    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

    0 讨论(0)
提交回复
热议问题