Remove messages before the response is rendered

Question:

I’ve got a page which contains 2 forms & allows updating of the model attached to each.

I’ve also got the messages framework integrated which for the most part is perfect. But after posting to this page you get two messages of success and I’d like to display 1 simple message in their place.

I’ve tried various approaches suggested in other questions;

Django: Remove message before they are displayed

Deleting/Clearing django.contrib.messages

But I’m unable to clear the message queue:

def post(self, request, **kwargs):
    profile_valid = False
    user_valid = False

    post_data = request.POST or None

    profile_form = self.profile_form_class(
        post_data,
        instance=request.user.profile,
        prefix='profile'
    )
    user_form = self.user_form_class(
        post_data,
        instance=request.user,
        prefix='user'
    )

    context = self.get_context_data(
        profile_form=profile_form,
        user_form=user_form
    )

    if profile_form.is_valid():
        profile_valid = True
        self.form_save(profile_form)
    if user_form.is_valid():
        user_valid = True
        self.form_save(user_form)

    if profile_valid and user_valid:
        # First get the messages from the above save methods
        storage = messages.get_messages(request)
        for message in storage:
            # Need to iterate over the messages to achieve what we need
            pass
        # Set the messages as used
        storage.used = True

        # Add our simple message
        messages.success(self.request, self.success_message)

    return self.render_to_response(context)

I’m using session based message storage, but that doesn’t seem to have an impact on what’s available in the view.

I’m using;

  • Django 2.2
  • Python 3.7
Asked By: markwalker_

||

Answers:

The solution here was to iterate over the loaded messages & del each one;

storage = messages.get_messages(request)
for _ in storage:
    # This is important
    # Without this loop `_loaded_messages` is empty
    pass

for _ in list(storage._loaded_messages):
    del storage._loaded_messages[0]

messages.success(self.request, "Details updated")

return self.render_to_response(context)

On the rendered page, I’m then presented with 1 message, “Details updated”.

This is similar to the solution proposed here; https://stackoverflow.com/a/30517135/9733868

Answered By: markwalker_

Try the code below to clear messages:

list(messages.get_messages(request))
Answered By: Kai – Kazuya Ito