class based view passing parameters

扶醉桌前 提交于 2019-12-13 04:13:51

问题


I have just started using Class-based views and I am trying to pass the parameters to class-based view as:

return HttpResponseRedirect(reverse('myView'), kwargs={'method': 'learning'})

My view is:

class MyView(View):
    form_class = MyForm
    initial = {'key': 'value'}
    template_name = 'algoRunning.html' 

    def dispatch(self, request, *args, **kwargs):
        print (kwargs['method'])
        data = self.readFile('myFile.txt')
        context = {'result': data}
        return render(request, self.template_name, context)

    def readFile(self, filePath):
        # read data
        return data

my url pattern looks like:

urlpatterns = [...    
url(r'^learning/(?P<method>[a-z]+)/$', my_views.MyView.as_view(), name='myView'),
..]

But, it gives me following error

Reverse for 'myView' with no arguments not found. 1 pattern(s) tried: ['learning/(?P<method>[a-z]+)/$']

What am I doing wrong??


回答1:


You have the parentheses in the wrong place. kwargs is a parameter to reverse, not to HttpResponseRedirect.

return HttpResponseRedirect(reverse('myView', kwargs={'method': 'learning'}))

Note, this could be shortened by using the redirect shortcut:

return redirect('myView', method='learning')



回答2:


kwargs should be reverse function's argument:

return HttpResponseRedirect(reverse('myView', kwargs={'method': 'learning'}))


来源:https://stackoverflow.com/questions/49157154/class-based-view-passing-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!