0

I've got Messages up and running; I can get a simple "submission successful" message to work so I know the context_processors and middleware are all configured properly. However, I'm trying to dynamically update the success message with data submitted in the form.

Here is my views.py:

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from menu.models import Book
from .forms import AddBook
from nextbook.models import Book
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.edit import CreateView


def library(request):
    form = AddBook(request.POST or None)
    success = False
    if request.method == 'POST':
        if form.is_valid():
            addedbook = form.save(commit=False)
            addedbook.save()
            form = AddBook()
            success = True
            messages.success(request, 'Book addition successful')


    return render(request, 'newbook/index.html', {'form': form})


class BookAddConf(SuccessMessageMixin, CreateView):
    model = Book
    success_message = "%(new_title)s by %(new_author)s was added to your library"

    def get_success_message(self, cleaned_data):
        return self.success_message % dict(
            cleaned_data,
            new_title=self.object.title,
            new_author=self.object.author
        )

I'm trying to get success_message to display when the user submits the form, populating the message with the data they entered. I've read through a dozen answers here on SO, but can't seem to find the right info to connect the last dots.

Here's my template:

{% if messages %}
  <ul class="messages">
      {% for message in messages %}
      <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
      {% endfor %}
  </ul>
  {% endif %}

I know I'm missing something, but I'm not sure what.

Mandelliant
  • 36
  • 1
  • 6
  • What happens instead? Is there an error message? What do you see when you click View Source in your browser? – Selcuk Jul 26 '18 at 01:15
  • @Selcuk right now I just get a message saying, "Book addition successful" which is the message.success in the view. There's no error message; it doesn't look like my success message in my class is being utilized. – Mandelliant Jul 26 '18 at 01:32

1 Answers1

0

Try this:

{% if messages %}
    <ul class="messages">
    {% for message in messages %}
        <li {% if message.tags %} class="{{message.tags}}" {% endif %}>
            <i class="bi bi-exclamation-triangle-fill"></i>
            {{ message }}
        </li>
    {% endfor %}
    </ul>
{% endif %}
Blye
  • 619
  • 4
  • 20
Null
  • 1
  • 2