Can I redirect to another url in a django TemplateView?

烈酒焚心 提交于 2019-12-03 08:37:29

问题


I have a url mapping that looks like this:

url(r'^(?P<lang>[a-z][a-z])/$', MyTemplateView.as_view()),

There are only a few values that I accept for the lang capture group, that is: (1) ro and (2) en. If the user types http://server/app/fr/, I want to redirect it to the default http://server/app/en/.

How can I do this since MyTemplateView only has a method that is expected to return a dictionary?

def get_context_data(self, **kwargs):
    return { 'foo': 'blah' }

回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/7884766/can-i-redirect-to-another-url-in-a-django-templateview

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