问题
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