我可以重定向到 django TemplateView 中的另一个 url 吗? [英] Can I redirect to another url in a django TemplateView?

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

问题描述

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

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

对于 lang 捕获组,我只接受几个值,即:(1) ro 和 (2) en.如果用户输入http://server/app/fr/,我想把它重定向到默认的http://server/app/en/.>

由于 MyTemplateView 只有一个预期返回字典的方法,我该怎么做?

def get_context_data(self, **kwargs):返回{'foo':'等等'}

解决方案

我知道这个问题很老,但我自己才刚刚完成.您可能认为要在 get_context_data 中执行此操作的一个原因是业务逻辑,但您应该将其放在 dispatch 中.

def dispatch(self, request, *args, **kwargs):如果不是 request.user.is_authenticated():返回重定向('家')return super(MyTemplateView, self).dispatch(request, *args, **kwargs)

在您的 dispatch 中保留您的业务逻辑,您应该是金子.

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 中的另一个 url 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆