Let's say that we want to show a message to the user when he or she adds a task. How do we do that? Well, the most simple way would be to use Django's built in messages framework.
If you open up settings.py, you'll notice that it's already added to the list of INSTALLED_APPS.
So let's open up the task/views.py and do some changes:
from django.contrib import messages # New, 1
...
@login_required
def frontpage(request):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'The task was added', extra_tags='is-success') # New, 2
else:
form = TaskForm()
title = 'This is a variable'
tasks = Task.objects.filter(user=request.user)
categories = Category.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(tasks, 10)
try:
tasks = paginator.page(page)
except PageNotAnInteger:
tasks = paginator.page(1)
except EmptyPage:
tasks = paginator.page(tasks.num_pages)
return render(request, 'task/frontpage.html', {'title': title, 'tasks': tasks, 'categories': categories, 'form': form})
So we didn't add more than 2 lines, but it's everything we need in the backend.
1: First, we import the method from Django.
2: Then, we add a new message to the session after the task is gone.
We specify the text and also add a optional parameter called "extra_tags". This is not necessary, but I want to do it to get some styling from Bulma.
Django has a lot of other options for the messages. If you want to learn more about them, you can read it here: https://docs.djangoproject.com/en/4.0/ref/contrib/messages/
Great, let's open up the base.html file and show the messages there:
...
<nav class="navbar is-dark">
...
</nav>
{% if messages %}
{% for message in messages %}
<div class="notification {{ message.tags }}">{{ message }}</div>
{% endfor %}
{% endif %}
...
So here we check if there are any messages, and if there are, we loop through them. The {{ message.tags }} is the "extra_tags".
So when the message is added to the system (in views.py), it's waiting to be shown. And as soon as it's shown, it will not appear again. So if you refresh, the message is gone :-)
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page
- 16. Separate url files and why
- 17. Adding tasks in the front end
- 18. Editing tasks
- 19. Completing and deleting tasks
- 21. Prettying up the design a little bit
- 22. Make it possible to sign up
- 23. Logging in
- 24. Logging out
- 25. Show only your data
- 26. Creating a model function
- 27. Template filters
- 28. Pagination
- 29. The Messages Framework