Show messages using django messages framework from one particular view

1.8k Views Asked by At

I'm using Django messages framework to show a success message in my contact page template when contact form submission is succeed.

since installed app, middlewares and context processor for messages are set in settings.py all the messages that are being generated showing in my contact template, for instance, Login success, logout success, and so on.

I just want to show the message.success in the contact templete that I defined in contact view:

def contact(request):
    if request.method == 'POST':
        Contact.objects.create(
            first_name=request.POST.get('first_name', ''),
            last_name=request.POST.get('last_name', ''),
            email=request.POST.get('email', ''),
            subject=request.POST.get('subject', ''),
            message=request.POST.get('message', ''),
        )
        # I want to show only this message on 'POST' success of this view
        messages.success(request, "Your message has been submitted.")
    return render(request, 'contact/contact.html')

my template:

<div class="success-message">
    {% if messages %}
        <ul class="messages">
            {% for message in messages %}
                <li class="{{ message.tags }}">
                    <h4 class="alert-success text-center" style="padding-top: 5px; padding-bottom: 5px;">
                        {{ message }}
                    </h4>
                </li>
            {% endfor %}
         </ul>
     {% endif %}

</div>

my template is showing all the messages that are being generated throughout the website along with the one that I want. how to prevent other messages except the one that I want?

What is the workaround for this problem, Can somebody help me through this?

1

There are 1 best solutions below

4
On

You should clear the messages, then add your success message, then render the template.

def contact(request):
    if request.method == 'POST':
        ...
        list(messages.get_messages(request))
        messages.success(request, "Your message has been submitted.")
    return render(request, 'contact/contact.html')