Garvit Jain
Garvit Jain

Reputation: 635

Django Add messages.error message to FormView

I need to show an error message after form submission to the user. The condition is set inside the form_valid function of FormView but it is not form specific and I do not want to change the existing form logic. This is what I have tried -

def form_valid(self, form):
    ...
    if condition:
        messages.error(self.request, 'Please ...')
    return super(...)

Also tried this -

def form_valid(self, form):
    ...
    if condition:
        self.message = 'Please ...'
    return super(...)

def get_success_url(self):
    if self.message:
        messages.add_message(self.request, messages.ERROR, self.message)
    return self.success_url

Both of them don't work. In DeleteView this can be done by overriding delete function, how to do it for FormView?

Upvotes: 1

Views: 3198

Answers (1)

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

your first way is right but you need to also add to this in your html template so in views.py

from django.contrib import messages
def form_valid(self, form):
    ...
    if condition:
        messages.error(self.request, 'Please ...')
    return super(...)

in HTML Template add this

{% if messages %}
<ul class="alert alert-danger" style="list-style: none;">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

Upvotes: 1

Related Questions