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.