【问题标题】:how to redirect url in django's templateview如何在 Django 模板视图中重定向 url
【发布时间】:2013-07-05 07:13:54
【问题描述】:

我有一个模板视图,代码在这里,怎么做

class MyTemplateView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super(UBaseTemplateView, self).get_context_data(**kwargs)
        # i want to redirect another url in here
        # how to do it

        return context

【问题讨论】:

标签: django redirect


【解决方案1】:

嗯,你会是这样的:

class MyTemplateView(TemplateView):
    def get(self, request, *args, **kwargs):
        return HttpResponseRedirect('/<your path here>/')

您可以通过here了解更多信息,并在here了解更多详情。

如果你想传递帖子数据,那么你所要做的就是:

class MyTemplateView(TemplateView):
    def get_context_data(self, **kwargs):
        return HttpResponseRedirect(reverse('/<your url here>/', [params]))

您也可以使用post 函数来执行此操作。

class MyTemplateView(TemplateView):
    def post(self, request, *args, **kwargs):
        # do what you want with post data
        # you can get access via request.POST.get()
        return HttpResponseRedirect('/<your url>/')
        # Or use the above example's return statement, if you want to pass along parameters

【讨论】:

  • 我知道这种方式。但是我在 get_context_data(self, **kwargs) 中处理发布数据,所以我想在完成发布数据后重定向另一个 url
  • 我不建议在get_context_data 步骤中重定向,将逻辑保留在您的帖子中或获取它所属的方法。完全可以通过返回您的get_context_data 方法来确定要做什么
  • @Hedde:我同意,最好使用getpost 为你做这种事情,你也获得了更多的灵活性。
  • 使用 post 方法是我想做的一个想法,并采用一种方法
【解决方案2】:

更通用的方法是使用 dispatch(),如 here 所述。关于 dispatch 的更多背景信息是in the Django docs

优势在于,无论在请求中指定的任何 HTTP 方法(GET、PUT、POST 等)都可以使用,而 get() 函数只有在方法为 GET 时才会被调用。

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多