Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting a View to another View in Django Python

Tags:

python

django

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'
like image 277
0leg Avatar asked Jan 21 '15 16:01

0leg


People also ask

What is permanent redirect in Django?

Permanent redirects are for when resource URLs change.

What is the difference between render and redirect in Django?

The render function Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text. You request a page and the render function returns it. The redirect function sends another request to the given url.

What is reverse redirect in Django?

the actual reverse function is used for performing the reverse happen. This method will be responsible for getting the new url value reversed. With the reverse function the name of the redirect url has to be specified. The name of url value specified here will for the redirect url name from the url's.py file.


2 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')
like image 159
Daniel Roseman Avatar answered Nov 15 '22 21:11

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')
like image 42
Henrik Andersson Avatar answered Nov 15 '22 20:11

Henrik Andersson