Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make django messages StackOverflow style?

I'd like to use Django's Messages module, however, I would like my messages to persist until the user clicks an X next to the message as opposed to having messages disappear as soon as the user reloads the page.

I am stumped with two issues: How do I make the messages' context processor not delete the messages once they are accessed? How do I later on delete the message from the DB explicitly once the user clicks on the "remove" button (which invokes an ajax call)?

Thanks!

like image 357
Yuval Cohen Avatar asked Jun 19 '10 16:06

Yuval Cohen


4 Answers

In your case django.contrib.messages won't bring you anywhere good. It's a message system inspired by RoR flash system, where messages aren't supposed to stay around

You should create your own messaging system (django-persistent-messages maybe?) that would save messages for registered users in database.

  • It's a fairly trivial task to implement
  • a model with a foreign key on User
  • a context processor to have the messages available in the templates
  • a view to consume a message
  • maybe a helper function to create the messages

Don't forget to make it available to others if you do so =)

like image 70
Guillaume Esquevin Avatar answered Nov 14 '22 07:11

Guillaume Esquevin


Since 1.2, Django has a new messages framework--django.contrib.messages--that is now completely detached from the auth module and offers much more functionality. For instance, it provides a basic way of handling the expiration of messages.

You can also take a look at the django-cnotes application that provides a simple cookie based user notification system. Setting constant CNOTES_AUTO_CLEAR to False prevents clearing the notes automatically.

And there is django-notices, yet another replacement for the built-in message notification system. It does no magic but provides an elegant and simple API.

like image 29
viam0Zah Avatar answered Nov 14 '22 08:11

viam0Zah


Since late 2010, there is the library, django-persistent-messages, for exactly this goal. It's reasonably well documented and works well to create a Stack Overflow-style messaging system.

It also integrates with the built-in Django messaging system, so the code changes are relatively minor, and you can still use the original system for messages that don't need to be persistent.

like image 4
Herman Schaaf Avatar answered Nov 14 '22 06:11

Herman Schaaf


Django messages might seem like a good starting point, but require contortions to get to where you want to go, and I wouldn't trust that future release of Django wouldn't break your hacks.

Implementing your own UserMessage model will probably serve you better in the long run. That gives you complete, unambiguous control over the message lifecycle. It might make a nice reusable app, too.

like image 2
Dave W. Smith Avatar answered Nov 14 '22 06:11

Dave W. Smith