[Django]-Django redirect to view

41👍

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)

6👍

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/

0👍

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 session 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! #}

-2👍

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.

Leave a comment