I
I
Igor Malyshev2015-11-11 02:42:28
Django
Igor Malyshev, 2015-11-11 02:42:28

How to display messages?

There is an abstract example. As a result, you need to output success_message to the template. But the end result is a blank page. All imports are present. Tell me what's wrong?
models.py:

class Author(models.Model):
    name = models.CharField(max_length=200)

urls.py:
url(r'^example/$', AuthorCreate.as_view()),
views.py:
class AuthorCreate(SuccessMessageMixin, ListView):
    model = Author
    template_name = "example.html"

    success_message = "Hello world"

example.html:
{% if messages %}
    {% for message in messages %}
        <p{% if message.tags %} class="{{message.tags}}"{% endif %}>{{message}}</p>
    {% endfor %}
{% endif %}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oscar Django, 2015-11-11
@winordie

Have you looked at the source at all? If so, here they are:

class SuccessMessageMixin(object):
    """
    Adds a success message on successful form submission.
    """
    success_message = ''

    def form_valid(self, form):
        response = super(SuccessMessageMixin, self).form_valid(form)
        success_message = self.get_success_message(form.cleaned_data)
        if success_message:
            messages.success(self.request, success_message)
        return response

    def get_success_message(self, cleaned_data):
        return self.success_message % cleaned_data

I translate :
success_message outputs the form_valid method, which in turn is called from the post method when submitting the form when it does not contain errors. The ListView does not contain any forms, so by definition it cannot display a message in any way.

S
sim3x, 2015-11-11
@sim3x

https://docs.djangoproject.com/en/1.8/ref/class-ba...

class AuthorCreate(SuccessMessageMixin, ListView):
    model = Author
    template_name = "example.html"

    def get_context_data(self, **kwargs):
        context = super(AuthorCreate, self).get_context_data(**kwargs)
        context['some_text_to_tpl'] = "Hello world"
        return context


#html
{{ some_text_to_tpl }}

To create, use CreateView https://docs.djangoproject.com/en/1.8/ref/class-ba...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question