Django class based generic view redirect

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")

Tags:

Python

Django