Login

SessionMessages

Author:
beiske
Posted:
July 31, 2008
Language:
Python
Version:
.96
Score:
0 (after 2 ratings)

Creates a message list, but unlike the messaging system in django.contrib.auth it is session-persistent and can therefor be displayed after a redirect.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class SessionMessageContainer:
    """
        In a view create messages with:
        SessionMessageContainer.append_to_session(request.session, u"Order with id: %s saved"%order.id)

        Output in template with:
        <ul class="messagelist">
            {% for message in request.session.messages.get_and_clear %}
            <li>{{message}}</li>
            {% endfor %}
        </ul>
    """
    def append(self, message):
        self.messages.append(message)
    def get_and_clear(self):
        from django.contrib.sessions.backends.db import SessionStore
        messages = self.messages
        self.messages=[]
        s = SessionStore(session_key=self.key)
        s['messages']=self
        s.save()
        return messages
    def __init__(self, key):
        self.key = key
        self.messages = []
    @staticmethod
    def append_to_session(session, message):
        messages = session.get('messages', SessionMessageContainer(key=session.session_key))
        messages.append(message)
        session['messages']=messages

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.