Can I redirect to another url in a django TemplateView?

馋奶兔 提交于 2019-12-02 22:25:51

I know this question is old, but I've just done this myself. A reason you may think you want to do it in get_context_data is due to business logic, but you should place it in dispatch.

def dispatch(self, request, *args, **kwargs):
    if not request.user.is_authenticated():
        return redirect('home')

    return super(MyTemplateView, self).dispatch(request, *args, **kwargs)

Keep your business logic in your dispatch and you should be golden.

Why only get_context_data?

Just set up your get handler to do a redirect if necessary.

def get(self, request, lang):
    if lang == 'fr':
         return http.HttpResponseRedirect('../en')

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