Messages and Logging
After submitting the form, a visitor is redirected to the animal's page, and nothing on it confirms that the application was saved. We also want a log message in the server's output each time an application is saved.
A One-Time Message
Django's messages framework stores a message for the next page a visitor loads. startproject sets it up: django.contrib.messages is in INSTALLED_APPS, and its middleware is in MIDDLEWARE.
A view adds a message with a function from the django.contrib.messages module, such as messages.success(), which takes the request and the message's text:
messages.success(request, "Thanks! We have your application.")
In AdoptView, the message goes in form_valid(), after the parent's version saves the application. We'll add it in the exercise.
Any page can be the one a redirect lands on, so messages are shown by the base template. Our templates/base.html has a loop above the content block that writes out each one:
<main>
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% block content %}{% endblock %}
</main>
Any template rendered with a request has messages in its context, and each message is shown once.
A Log Message
Python's logging module drops our app's INFO messages by default. The starting branch's LOGGING setting in config/settings.py writes them to the terminal. animals/views.py creates the module's logger below its imports:
logger = logging.getLogger(__name__)
In the exercise, form_valid() logs each saved application with logger.info(). Logs are kept and copied, so the message records only the application's id and the animal's, with no applicant details. The message is written only for applications submitted through the site's form, not ones added in the admin.