How do I redirect in Django with context?

django redirect with parameters
django redirect with context
django redirect url
django redirect with kwargs
django rest framework redirect
django httpresponseredirect with context
django redirect to same page
django redirect with message

I have a view that validates and saves a form. After the form is saved, I'd like redirect back to a list_object view with a success message "form for customer xyz was successfully updated..."

HttpResponseRedirect doesn't seem like it would work, because it only has an argument for the url, no way to pass dictionary with it.

I've tried modifying my wrapper for object_list to take a dict as a parameter that has the necessary context. I the return a call to this wrapper from inside the view that saves the form. However, when the page is rendered, the url is '/customer_form/' rather than '/list_customers/'. I tried modifying the request object, before passing it to the object_list wrapper, but that did not work.


Please note the answer suggested here is only applicable to Django < 1.2:

Do you have control over the view that you are redirecting to? In that case you can save the context in the session before redirecting. The target view can pick up the context (and delete it) from the session and use it to render the template.

If your only requirement is to display a message then there is a better way to do this. Your first view can create a message for the current using auth and have the second view read and delete it. Something like this:

def save_form(request, *args, **kwargs):
    # all goes well
    message = _("form for customer xyz was successfully updated...")
    request.user.message_set.create(message = message)
    return redirect('list_view')

def list_view(request, *args, **kwargs):
    # Render page

# Template for list_view:
{% for message in messages %}
{% endfor %}

Messages are saved to the database. This means that you can access them even after a redirect. They are automatically read and deleted on rendering the template. You will have to use RequestContext for this to work.

For Django => 1.2 read the answer involving messages

The Ultimate Guide to Django Redirects – Real Python, Please note the answer suggested here is only applicable to Django < 1.2: Do you have control over the view that you are redirecting to? In that� In Django, redirection is accomplished using the 'redirect' method. The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name. The myapp/views looks like the following so far −

request.user.message_set was deprecated in Django 1.2 and has been removed since Django 1.4, the message framework should be used instead.

from django.contrib import messages

# messages.add_message(request, level, message, extra_tags='', fail_silently=False)
messages.add_message(request, messages.INFO, "Your Message")

Messages can then be rendered on the template with:

{% if messages %}
    <ul class="messages">
        {% for message in messages %}
            <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
        {% endfor %}
{% endif %}

How do I redirect in Django with context?, render() �. render (request, template_name, context=None, content_type=None, An absolute or relative URL, which will be used as-is for the redirect location. In Django, you redirect the user to another URL by returning an instance of HttpResponseRedirect or HttpResponsePermanentRedirect from your view. The simplest way to do this is to use the function redirect () from the module django.shortcuts.

To expand on Antoine's helpful answer: if you want to process the messages in your views module, rather than the template:

from django.contrib.messages import get_messages

def my_view(request):
    # Process your form data from the POST, or whatever you need to do

    # Add the messages, as mentioned above
    messages.add_message(request, messages.INFO, form.cleaned_data['name'])

    return HttpResponseRedirect('/other_view_url/')

def other_view(request):
    storage = get_messages(request)
    name = None
    for message in storage:
        name = message
    return render(request, 'general/other_view.html', {'name': name})

Django shortcut functions | Django documentation, return render(request, "../../xyz. html", context=context)def view2(request) : .. Now, if you want to redirect to view1 from view2 along with its context, you can modify your functions like this. If you’re running a “reverse proxy” web server around your application, you can configure the redirect there. Most Django applications use such a web server, and this tends to be where their WWW redirect ends up. It’s appealing since most web servers allow you to do it with a little standard configuration.

I found the following to work if more than just a message needs to be added to the redirect:

from django.shortcuts import redirect
import urllib

def my_view(request):


    context = {'foo1': bar1, 'foo2': bar2, 'foo3': bar3}
    return redirect('/redirect_link/?' + urllib.parse.urlencode(context))

See also how to pass context data with django redirect function?

Django redirect with custom context | by Ayush Goyal, Django - Page Redirection - Page redirection is needed for many reasons in web application. You might want to redirect a user to another page when a specific� from django.shortcuts import redirect. The function redirect will basically return an HttpResponseRedirect with the proper URL. I prefer to always use this shortcut so my codebase remains consistent.

In Django 2.x + you can simply use messages framework that comes with Django

from django.contrib import messages

def register(request):
    messages.success(request,"You have registered successfully, now login!")
    return redirect('login-page')

And in you, login.html template do add this code

  {% if messages %}
    {% for message in messages %}
        <div class="alert alert-success alert-dismissible fade show">
            <strong>Success!</strong> {{message}}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
    {% endfor %}
 {% endif %}

Note this example can be applied to anywhere you want to display a message for success

If you want to pass an error message simply use messages.error(request, "Error message")

Django - Page Redirection, All the shortcuts are availablein the module django.shortcuts. the only difference is that it does not pass the request to the context. redirect. Params: def redirect(to, *args, **kwargs):. Returns an HttpResponseRedirect (or� 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.

Django Shortcuts, from django.shortcuts import redirect. The function redirect will basically return an HttpResponseRedirect with the proper URL. I prefer to� A common way of making this work is to create a hidden field within the login form on the login page and use this hidden field to obtain the value of the next parameter in the URL with the variable and passing this to the file, where we can then redirect to this page after the login.

Django Tips #1 redirect, It accepts a string path to redirect to. To use HttpResponseRedirect you have to import it from django.http module. HttpResponseRedirect sends a client-side redirect (HTTP status code 302) to the browser, and then the browser re-requests another page. You can set a URL query string on the redirect, though that will be visible to the user and anyone intercepting HTTP requests (i.e. proxies), and is therefore not suitable for sensitive information.

Redirecting URLs in Django, Django: redirect with context variable or something. So i have a home page where people can sign up or log in. When they try to log in it redirects to /login. html,� Search for information in the archives of the django-users mailing list, or post a question. #django IRC channel Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before. Ticket tracker Report bugs with Django or Django documentation in our ticket tracker. Download:

  • Note to future searchers: Be sure to read on past the accepted answer, as it is now deprecated.
  • The other answer should probably be accepted as the correct answer now. This was deprecated in django 1.2 and removed in django 1.4 (as mentioned in the other answer).
  • I would add that you can use {{ message.level_tag }} to show the level tag. success etc. which can be useful tor styling alert-{{ message.level_tag }} for instance