[Fixed]-How to redirect from a view to another view In Django

23👍

You can use redirect from http shortcuts.

from django.shortcuts import redirect

def my_view(request):
    ...
    object = MyModel.objects.get(...)
    return redirect(object) #or return redirect('/some/url/')

Here is the link to official docs.

👤mdegis

34👍

As already suggested by @mdegis you can use the Django redirect function to redirect to another view or url.

from django.shortcuts import redirect

def view_to_redirect_to(request):
    #This could be the view that handles the display of created objects"
    ....
    perform action here
    return render(request, template, context)

def my_view(request):
    ....
    perform form action here
    return redirect(view_to_redirect_to)

Read more about redirect here and here

You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you’re redirecting to.

In urls.py

from news import views

url(r'^archive/$', views.archive, name='url_to_redirect_to')

In views.py

from django.urls import reverse

def my_view(request):
    ....
    return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value}))

More about reverse Here

0👍

To redirect from a view to another view, you need to give the conbination of the app name "myapp", colon ":" and the view name "dest_view" which is set in the path in "myapp/urls.py" as shown below. And, you don’t need to modify the path in "myapp/urls.py" if you pass data with session with request.session[‘key’] as shown below:

# "myapp/views.py"

from django.shortcuts import render, redirect

def redirect_view(request):
    # Here
    request.session['person'] = {'name': 'John', 'age': 27}
                    # Here
    return redirect("myapp:dest_view")

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

You need to give the view name "dest_view" to 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('dest/', views.destination_view, name="dest_view")
]

Then, this is Django Template:

# "myapp/index.html"

{{ request.session.person.name }} {# John #}
{{ request.session.person.age }}  {# 27 #}

0👍

from django.urls import reverse

def my_view(request):
    ....
    return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value(object.id for specific id)}))

Leave a comment