Django:在传递视图中使用HttpResponseRedirect(reverse())访问kwargs

时间:2018-03-22 15:12:45

标签: python django python-3.x url httpresponse

我试图在成功视图中访问通过HttpResponseRedirect()传递的kwargs。密钥存在于kwarg dict中,但价值不是。这是为什么?

查看:

class UploadView(View):

    paneluploadform = PanelUploadForm

    def get(self, request, *args, **kwargs):

        paneluploadform = self.paneluploadform()
        context = {'paneluploadform': paneluploadform}
        return render(request, 'results/upload.html', context)


    def post(self, request, *args, **kwargs):

        paneluploadform = self.paneluploadform(request.POST, request.FILES)

        if paneluploadform.is_valid():
            panel_name = paneluploadform.upload()
            return HttpResponseRedirect(
                    reverse('results:success',
                    kwargs={'panel_name': panel_name})
                )


        context = {'paneluploadform': paneluploadform}
        return render(request, 'results/upload.html', context)


def success(request, *args, **kwargs):

    return render(request, 'results/success.html')

urls.py:

urlpatterns = [
    url(r'^upload/$', UploadView.as_view(), name='upload'),
    url(r'^upload/successful-(?P<panel_name>)', success, name='success')
]

在我的success.py视图中,print(kwargs)输出为{'panel_name': ''}

但我的网址是/ localhost / upload / successful-panelnameientered

为什么没有kwargs ={'panel_name': 'panelnameientered'}

1 个答案:

答案 0 :(得分:1)

我不完全确定,但我认为您应该使用re_path,而且您没有设置模式以匹配successful-之后的模式。所以应该是这样的:

re_path(r'^upload/successful-(?P<panel_name>[a-z]+)', success)