0leg
0leg

Reputation: 14124

Redirecting a View to another View in Django Python

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'

Upvotes: 9

Views: 21243

Answers (3)

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 FooView(request):
                    # Here
    return redirect("myapp:bar")

def BarView(request):
    return render(request, 'myapp/index.html', {})

Upvotes: 0

Henrik Andersson
Henrik Andersson

Reputation: 47172

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

Upvotes: 6

Daniel Roseman
Daniel Roseman

Reputation: 599450

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

Upvotes: 26

Related Questions