Consider the following:
urls.py:
urlpatterns = patterns('',
('^test/$', ClassView.as_view()),
)
views.py:
class ClassView(View):
def get(self, request):
return HttpResponse("test")
def post(self, request):
# do something
return redirect(ClassView.get(request)) # What should I do to redirect to a class here without specifying the path?
I want to redirect to ClassView's get function (/test/), but when I try the above I get:
NoReverseMatch at /test/
So it obviously finds the URL but says that there's no match?
You should just name your urlpattern and redirect to that, that would be the most Django-ey way to do it.
It's not documented (so not guaranteed to work in future Django versions) but the redirect
shortcut method can take a view function, so you can almost do redirect(ClassView.as_view())
...I say almost because this doesn't actually work - every time you call as_view()
you get a new view function returned, so redirect
doesn't recognise that as the same view as in your urlconf.
So to do what you want, you'd have to update your urlconf like so:
from .views import test_view
urlpatterns = patterns('',
('^test/$', test_view),
)
And in your views.py
class ClassView(View):
def get(self, request):
return HttpResponse("test")
def post(self, request):
# do something
return redirect(test_view)
test_view = ClassView.as_view()
But I still think you should do it the other way:
urlpatterns = patterns('',
url('^test/$', ClassView.as_view(), name="test"),
)
.
class ClassView(View):
def get(self, request):
return HttpResponse("test")
def post(self, request):
# do something
return redirect("test")
May be you should set name to your urlpattern and redirect to that name?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With