2

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

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
4

2 回答 2

7

好吧,你会是这样的:

class MyTemplateView(TemplateView):
    def get(self, request, *args, **kwargs):
        return HttpResponseRedirect('/<your path 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
于 2013-07-05T08:02:48.087 回答
0

一种更通用的方法是使用 dispatch() ,如此处所述。关于 dispatch 的更多背景信息在 Django 文档中。

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

于 2015-02-18T17:26:29.960 回答