Django redirect to view

Question:

I have a view that I then want to redirect to another view with a success message. The signature of the method that I want to redirect to is:

quizView(request, quizNumber, errorMessage=None, successMessage=None)

And my attempt at redirecting to that view is:

return redirect(quizView, quizNumber=quizNumber, errorMessage=None, successMessage="Success!")

I’ve tried almost every combination of named and un-named parameters, but it doesn’t work. Also, I tried just returning the the second view with the first, but then the URL is still where it was in the old view instead of appearing as though it has redirected. Is there a way to make this work?

Asked By: user1056805

||

Answers:

Can you try example 2 given in https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect

  • Make sure that it does the ‘reverse’ on the given view.
  • Your view name should be wrapped in single quotes/

You haven’t given your URL a name, so you need to use the whole path to the view function. Plus, that URL doesn’t take errorMessage or successMessage parameters, so putting them into the reverse call will fail. This is what you want:

return redirect('quizzes.views.quizView', quizNumber=quizNumber)
Answered By: Daniel Roseman

You should Refer this https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#redirect

For redirect inside view. Its very easy either you redirect using creating a url for view or call inside the view also.

Answered By: Mayank Pratap Singh

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

Then, you need the conbination of the app name "myapp", colon ":" and the view name "quizView" as shown below. In addition, you don’t need to import the view "quizView" in "myapp/views.py". And, you don’t need to modify path() in "myapp/urls.py" if you pass data with "post" method with request.session[‘key’] as shown below:

# "myapp/views.py"

from django.shortcuts import render, redirect

def my_view(request): # Here
    request.session['quizNumber'] = 3
    request.session['errorMessage'] = None
    request.session['successMessage'] = "Success!"

                    # Here
    return redirect("myapp:quizView")

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

Then, this is Django Template:

# "myapp/index.html"

{{ request.session.quizNumber }}     {# 3 #}
{{ request.session.errorMessage }}   {# None #}
{{ request.session.successMessage }} {# Success! #}
Answered By: Kai – Kazuya Ito