Search code examples
djangodjango-messages

Store messages after showing in the template


I would like to store the last messages to get a chance for the user to check it again.

How can I save it, after show? before show? Do I need to implement a db model?


Solution

  • I found a nice solution, without using external library. Just with my lovely python!

    First I create a function to store the messages into a database:

    def save_messages(message):
        db.objects.add(ManyToMany.object.create(message))
        return redirect('message_saved')
    

    and then I put the function to run anytime a message is being sent into contrib messages itself

    MYPROJECT\venv\Lib\site-packages\django\contrib\messages\api.py

    def add_message(request, level, message, extra_tags='', fail_silently=False):
    """
    Attempt to add a message to the request using the 'messages' app.
    """
    try:
        messages = request._messages
    except AttributeError:
        if not hasattr(request, 'META'):
            raise TypeError(
                "add_message() argument must be an HttpRequest object, not "
                "'%s'." % request.__class__.__name__
            )
        if not fail_silently:
            raise MessageFailure(
                'You cannot add messages without installing '
                'django.contrib.messages.middleware.MessageMiddleware'
            )
    else:
        from WALLAWALLA import save_messages
        save_messages(message) 
        return messages.add(level, message, extra_tags)
    

    and this really works great