How to pass information using an HTTP redirect (in Django)

I have a view that accepts a form submission and updates a model.

After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.

How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done before on other sites. How is this accomplished?


Asked by: David462 | Posted: 30-11-2021






Answer 1

This is a built-in feature of Django, called "messages"

See http://docs.djangoproject.com/en/dev/topics/auth/#messages

From the documentation:

A message is associated with a User. There's no concept of expiration or timestamps.

Messages are used by the Django admin after successful actions. For example, "The poll Foo was created successfully." is a message.

Answered by: Rafael257 | Posted: 01-01-2022



Answer 2

You can use django-flashcookie app http://bitbucket.org/offline/django-flashcookie/wiki/Home

it can send multiple messages and have unlimited types of messages. Lets say you want one message type for warning and one for error messages, you can write

def simple_action(request):
    ...
    request.flash['notice'] = 'Hello World'
    return HttpResponseRedirect("/")

or

def simple_action(request):
    ...
    request.flash['error'] = 'something wrong'
    return HttpResponseRedirect("/")

or

def simple_action(request):
    ...
    request.flash['notice'] = 'Hello World'
    request.flash['error'] = 'something wrong'
    return HttpResponseRedirect("/")

or even

def simple_action(request):
    ...
    request.flash['notice'] = 'Hello World'
    request.flash['notice'] = 'Hello World 2'
    request.flash['error'] = 'something wrong'
    request.flash['error'] = 'something wrong 2'
    return HttpResponseRedirect("/")

and then in you template show it with

{% for message in flash.notice %}
    {{ message }}
{% endfor }}

or

{% for message in flash.notice %}
    {{ message }}
{% endfor }}
{% for message in flash.error %}
    {{ message }}
{% endfor }}

Answered by: Brad304 | Posted: 01-01-2022



Answer 3

I liked the idea of using the message framework, but the example in the django documentation doesn't work for me in the context of the question above.

What really annoys me, is the line in the django docs:

If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.

which is incomprehensible to a newbie (like me) and needs to expanded upon, preferably with what those 2 options look like.

I was only able to find solutions that required rendering with RequestContext... which doesn't answer the question above.

I believe I've created a solution for the 2nd option below:

Hopefully this will help someone else.

== urls.py ==

from django.conf.urls.defaults import *
from views import *

urlpatterns = patterns('',
    (r'^$', main_page, { 'template_name': 'main_page.html', }, 'main_page'),
    (r'^test/$', test ),

== viewtest.py ==

from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def test(request):
    messages.success( request, 'Test successful' )
    return HttpResponseRedirect( reverse('main_page') )

== viewmain.py ==

from django.contrib.messages import get_messages
from django.shortcuts import render_to_response

def main_page(request, template_name ):
    # create dictionary of items to be passed to the template
    c = { messages': get_messages( request ) }

    # render page
    return render_to_response( template_name, c, )

== main_page.html ==

{% block content %}
    {% if messages %}
    <div>
        {% for message in messages %}
            <h2 class="{{message.tag}}">{{ message.message }}</h2>
        {% endfor %}
    </div>
    {% endif %}
{% endblock %}

Answered by: Luke542 | Posted: 01-01-2022



Answer 4

I have read and checked all answers, and it seems to me that the way to go now is using the messaging framework. Some of the replies are fairly old and have probably been the right way at the time of the posting.

Answered by: Catherine931 | Posted: 01-01-2022



Answer 5

There is a lot of solutions

1 Use Django-trunk version - it support sending messages to Anonymous Users

2 Sessions

def view1(request):
    request.session['message'] = 'Hello view2!'
    return HttpResponseRedirect('/view2/')


def view2(request):
    return HttpResponse(request.session['message'])

3 redirect with param

return HttpResponseRedirect('/view2/?message=Hello+view2')

4 Cookies

Answered by: John596 | Posted: 01-01-2022



Answer 6

Can you just pass the message as a query param oon the URL to which you're redirecting? It's not terribly RESTy, but it ought to work:

return HttpResponseRedirect('/polls/%s/results/?message=Updated" % p.id)

and have that view check for a message param, scrub it for nasties, and display it at the top.

Answered by: Anna408 | Posted: 01-01-2022



Answer 7

I think this code should work for you

request.user.message_set.create(message="This is some message")
return http.HttpResponseRedirect('/url')

Answered by: Chelsea165 | Posted: 01-01-2022



Answer 8

Take a look at Django's messages framework. http://docs.djangoproject.com/en/dev/ref/contrib/messages/#ref-contrib-messages

Answered by: Brad179 | Posted: 01-01-2022



Answer 9

You could also have the redirect url be the path to an already parameterized view.

urls.py:

(r'^some/path/(?P<field_name>\w+)/$', direct_to_template,
    {'template': 'field_updated_message.html',
    },
    'url-name'
),

views.py:

HttpResponseRedirect( reverse('url-name', args=(myfieldname,)) )

Note that args= needs to take a tuple.

Answered by: Lyndon427 | Posted: 01-01-2022



Answer 10

The solution used by Pydev UA is the less intrusive and can be used without modifying almost nothing in your code. When you pass the message, you can update your context in the view that handles the message and in your template you can show it.

I used the same approach, but instead passing a simple text, passed a dict with the information in useful fields for me. Then in the view, updated context as well and then returned the rendered template with the updated context.

Simple, effective and very unobstrusive.

Answered by: Samantha174 | Posted: 01-01-2022



Answer 11

While all suggestions so far work, I would suggest going with Ry4an's (pass it in the request URL) - just change the actual text to a coded text within a predefined set of text messages.

Two advantages here:

  1. Less chance of something hacking through your scrubbing of bad content
  2. You can localize your messages later if needed.

The other cookie related methods.. well, they don't work if the browser doesn't support cookies, and are slightly more expensive.. But only slightly. They're indeed cleaner to the eye.

Answered by: Emma542 | Posted: 01-01-2022



Similar questions

bash - Redirect command to input of another in Python

I would like to replicate this in python: gvimdiff &lt;(hg cat file.txt) file.txt (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" Getting to the python part... # hg...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


python - Django: Redirect to previous page after login

I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I ...


How to redirect the output of .exe to a file in python?

In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?


python - How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page. For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I wou...


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


How to redirect stderr in Python? Via Python C API?

This is a combination of my two recent questions: [1] Python instance method in C [2] How to redirect stderr in Python? I would like to log the output of both stdout and stderr from a python script. The thing I want to ask is...


How to redirect stderr in Python?

I would like to log all the output of a Python script. I tried: import sys log = [] class writer(object): def write(self, data): log.append(data) sys.stdout = writer() sys.stderr = writer() Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead. Ho...


linux - Redirect stderr to stdout on exec-ed process from python?

In a bash script, I can write: exec 2&gt;&amp;1 exec someprog And the stderr output of someprog would be redirected to stdout. Is there any way to do a similar thing using python's os.exec* functions? This doesn't have to be portable, just work on Linux.


python - How to set cookies with redirect in Pylons

In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top