Reputation: 6501
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?
Upvotes: 9
Views: 25308
Reputation: 160
Try return self.get()
. I didn't test. But as its a python code it should work. Use this if you only want to execute the statements. This will not return any HTTP 302 status I think.
Upvotes: 0
Reputation: 33923
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")
Upvotes: 8
Reputation: 898
def post(self, request, *args, **kwargs):
return HttpResponseRedirect(request.path)
This will redirect to the same URL as your post()
, and then get handled by your get()
.
Upvotes: 1
Reputation: 6797
May be you should set name to your urlpattern and redirect to that name?
Upvotes: 2