本文介绍了我可以在django TemplateView中重定向到另一个网址吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个url映射,如下所示:

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

只有几个我接受 lang 捕获组的值,即:(1) ro 和(2) EN 。如果用户键入 http:// server / app / fr / ,我想将其重定向到默认的 http:// server / app / en /



如何执行此操作,因为 MyTemplateView 只有一种方法预计会返回一个字典?

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


解决方案

我知道这个问题是旧的但我自己也是这样做的。您可能认为您希望在 get_context_data 中执行此操作的原因是由于业务逻辑,但您应将其放在 dispatch中

  def dispatch(self,request,* args,** kwargs):
如果没有request.user .is_authenticated():
返回重定向('home')

返回超级(MyTemplateView,self).dispatch(request,* args,** kwargs)

将您的业务逻辑保留在您的调度中,您应该是金色的。 p>

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' }
解决方案

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.

这篇关于我可以在django TemplateView中重定向到另一个网址吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:44