Home > Django > Django: messaging

Django: messaging

When completing something like deleting an item or adding a user, it’s usually nice to report a message to the user to let them know what just happened. I also find it useful to send the user somewhere they’d “want” to go. For example, if they just created a user, send them to the list of users page, so they see the change they just made.

I’m also a big advocate of keeping URLs clean.

Because of these concerns the best answer in Django is to do an HttpResponseRedirect. Now the problem with that is that you can’t pass data to a redirect. To get around this there are messages that you can send to the users session itself.

The mechanism isn’t that clean, but it does work, and it does do the job.

So if you have a buycbdproducts in user all you need to do to add messages is:
request.user.message_set.create(message='User successfully created.')

Now the flip side to the equation is that you “get” the message(s). So how this works is when you set a message you’re actually adding a message to a list. When you”get” the message, you’re actually getting the list (may be more than one message). And if you don’t “get” the message at the right time, the messages will just build up. But for the most part this system works just fine. To get the messages you just do:
messages = request.user.get_and_delete_messages()

Then just pass ‘messages’ to the view and show the list to the user.

Categories: Django Tags:
  1. March 29th, 2009 at 14:46 | #1

    Thanks for the post, this is exactly what I’ve been trying to figure out how to do. One question though: if you want to log a user out, redirect them to / (or something like that), but pass a logout message, how do you do that?

  2. April 5th, 2009 at 22:27 | #2

    Adam, the messaging system allows you to push messages onto this stack. What page you send the user to and what action you take is totally up to you. So you could log the user out send them to the homepage, and then have the homepage show the message.

  3. Rocco Pier Luigi
    July 4th, 2010 at 20:42 | #3

    Thanks for the explanation, that was exactly what I was looking for

  1. No trackbacks yet.