Redirecting a View to another View in Django Python

Question:

How does one redirect from one View to another (next-going one):

class FooView(TemplateView):
  template_name 'foo.html'

  def post(self, *args, **kwargs):
    return redirect(BarView)
    # return redirect(BarView.as_view()) ???

class BarView(TemplateView):
  template_name 'bar.html'
Asked By: 0leg

||

Answers:

Give the URL pattern itself a name in your urls.py:

url('/bar/', BarView.as_view(), name='bar')

and just pass it to redirect:

return redirect('bar')
Answered By: Daniel Roseman

You can use the redirect for that, if you’ve given the view a name in urls.py.

from django.shortcuts import redirect
return redirect('some-view-name')
Answered By: Henrik Andersson

You need to give the view name "bar" to the path in "myapp/urls.py" as shown below:

# "myapp/urls.py"

from django.urls import path
from . import views

app_name = "myapp"

urlpatterns = [                 # This is view name
    path('bar/', views.BarView, name="bar")
]

Then, you need the conbination of the app name "myapp", colon ":" and the view name "bar" as shown below. In addition, you don’t need to import the view "bar" in "myapp/views.py":

# "myapp/views.py"

from django.shortcuts import redirect

def my_view(request):
    return redirect("myapp:bar")
Answered By: Kai – Kazuya Ito