Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages to the user via django signals

Tags:

django

Forgive me if this question makes little sense; I have had little sleep as of late.

I want to send a notification to the user whenever a signal fires via django's messages module, but I am at a loss as to how to pass the request object to the messages.success method.

I'm doing this because whenever a user gets a badge I need to tell him about it. For example, when a user completes her profile, does a set number of ratings, or makes a certain number of comments a badge is rewarded. Right now the only way for the user to tell that she has a new badge is to go to the badge page, but I want to gently inform the user of the event.

Using django notifications would work, but the system we've got in place would be too jarring (currently it loads a modal) and more expensive since it hits the database.

Thanks in advance.

like image 406
IntrepidDude Avatar asked Aug 10 '10 02:08

IntrepidDude


People also ask

How do you use signals in Django?

There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.

What is the use of the Post_delete signal in Django?

To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.

Where is Pre_save signal in Django?

pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.


2 Answers

The Django messages framework operates against HTTP requests rather than users (so it also works for anonymous users). A signal would have no idea of which request to attach a message to, and chances are the user in question probably wouldn't even be logged in at the time.

It sounds like what you're trying to do would be better suited to something like django-notification, http://github.com/jtauber/django-notification/ .

like image 106
Rolo Avatar answered Nov 06 '22 16:11

Rolo


You can't use the messages framework directly in a signal because you don't have access to a request.

You could probably get around this by wrapping a view that the user is likely to go to frequently with something that checks for new badges and creates a message. Then although they wouldn't get the message on the very next page viewed after receiving the badge, they would get it on the first page viewed after the page that does the message creation.

like image 26
Duncan Parkes Avatar answered Nov 06 '22 14:11

Duncan Parkes