This is our seventeenth article in Django, in this article we are going to learn about Django Flash Messages with Message Framework .
so in a web application sometimes you need to display one-time notification message (also known as “flash message”) to the user after processing a form or some other types of user input.
For this, Django provides full support for cookie- and session-based messaging, for both anonymous and authenticated users. The messages framework allows you to temporarily store messages in one request and retrieve them for display in a subsequent request (usually the next one). Every message is tagged with a specific level
that determines its priority (e.g., info
, warning
, or error
).
Basically in this example we are going to create a simple registration form, when the user submit their information we want to show a flash message for them.
Flask Web Development Tutorials
1: Flask CRUD Application with SQLAlchemy
2: Flask Creating News Web Application
3: Flask Creating REST API with Marshmallow
Python GUI Development Tutorials
1: PyQt5 GUI Development Tutorials
2: Pyside2 GUI Development Tutorials
3: wxPython GUI Development Tutorials
4: Kivy GUI Development Tutorials
5: TKinter GUI Development Tutorials
So now we need to create a New Project in Django, also for django installation and creating New Project you can read this article Django Introduction & Installation. but you can use this command for creating of the New Project.
1 |
django-admin startproject DjangoProject |
After creating of the Django Project, you need to migrate your project. make sure that you have changed the directory to the created project.
1 |
python manage.py migrate |
So after doing this, let’s create our Django App, i have already talked about Django App in one of my articles, you can check this Django Apps & URL Routing.
1 |
python manage.py startapp MyApp |
After creation of the App, you need to add the created App in your settings.py file INSTALLED_APP section .
1 2 3 4 5 6 7 8 9 |
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp', ] |
Now open your models.py in your MyApp App, and add your model, this is a basic model with four fields, you can read my article on django models Django Models Introduction.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from django.db import models # Create your models here. class RegistrationData(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) def __str__(self): return self.username |
After adding a new model in Django, first you need to create migrations file and after that you need to add your model to the database, by default Django uses Sqlite database, for mysql database connection you can read this article Django Mysql Database Connection. make sure that you have changed directory to your project.
1 |
python manage.py makemigrations |
1 |
python manage.py migrate |
OK now let’s just add our model to the Django admin panel, you can read this article for django super user Django Creating Super User. open your admin.py file and add this code.
1 2 3 4 5 6 |
from django.contrib import admin from .models import RegistrationData # Register your models here. admin.site.register(RegistrationData) |
For the registration we need to create a form, and also we are using ModelForm in this article, you can read my complete article on ModelForm in this link Django Creating Form with Model Form.
it is a simple form based on our model that we have already created. the form will have four fields like username, password, email and phone.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from django import forms from .models import RegistrationData class RegistrationModel(forms.ModelForm): class Meta: model = RegistrationData fields = [ 'username', 'password', 'email', 'phone', ] widgets = { 'username':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Please Enter Username'}), 'password':forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Please Enter Password'}), 'email':forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Please Enter Email'}), 'phone':forms.NumberInput(attrs={'class':'form-control', 'placeholder':'Please Enter Phone'}), } |
Before adding our html files, we need to create our views, so open your views.py file and add this code for creating a simple view. and you can see in the view we have passed the form as context variable to the django template. the register() view is for rendering our form, and the addUser() view is for adding data from our form to the database. also you can see that after successful registration of the user we are going to create a Flash Message of success to the user. you need to import the Flash Message at the top, it is related to django.contrib package.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
from django.shortcuts import render, redirect from .forms import RegistrationModel from django.contrib import messages # Create your views here. def register(request): context = {"form":RegistrationModel} return render(request, "index.html", context) def addUser(request): modelform = RegistrationModel(request.POST) if modelform.is_valid(): modelform.save() messages.add_message(request, messages.SUCCESS, "Registration Was Successfull, Please Login") return redirect('register') |
So you can see that in the addUser() view function, we are going to tell Django , that after successful registration show a flash message to the user.
Now we need to render this Flash Message in our html file, so you need to create a new directory in your Django Project called templates, and in the templates folder add two html files, the first one is index.html and the second one is base.html. for django templates you can read this article Django Templates Introduction. also make sure that you have added your templates name in the templates section of settings.py file like this.
1 2 3 4 |
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], # templates name added here |
And this is our base.html, also you can see that in the base.html we have added the Bootstrap CDN link, because in this article we are going to use from Bootstrap styles. also you can check this article for adding styles to your Django Project Django Adding Bootstrap & CSS.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!-- CSS only --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>{% block title %}{% endblock %}</title> </head> <body> {% block body %} {% endblock %} </body> </html> |
You can show the Flash Message where ever you want in your html file using this code.
1 2 3 4 5 6 7 8 9 10 11 12 |
{% if messages %} {% for msg in messages %} <div class="alert alert-{{msg.level_tag}} " role="alert"> {{msg.message}} </div> {% endfor %} {% endif %} |
After adding that code , this is our complete index.html file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
{% extends 'base.html' %} {% block title %} Registration {% endblock %} {% block body %} <div class="container"> <h1>Registration Model Form</h1> <h3>Welcome to codeloop.org</h3> <h5>Django Tutorial - Tutorial Number 17 Django Flash Messages</h5> <hr/> {% if messages %} {% for msg in messages %} <div class="alert alert-{{msg.level_tag}} " role="alert"> {{msg.message}} </div> {% endfor %} {% endif %} <form action="{% url 'addUser' %}" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit" class="btn btn-primary"/> </form> </div> {% endblock %} |
Also you need to create your urls, you can read this article for url routing Django Apps & URL Routing . but just create a new python file in your MyApp app at name of urls.py and add these codes.
1 2 3 4 5 6 7 8 |
from django.urls import path from .views import register, addUser urlpatterns = [ path('', register, name = "register"), path('add/', addUser, name = "addUser"), ] |
And also you need to include your app urls.py in your project urls.py file.
1 2 3 4 5 6 7 8 |
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('MyApp.urls')) ] |
Now you can run your project and we have our simple form. also you can add data from this form to your database. so add some data and check your admin panel, you will have the added data. also you can see a nice flash message after adding submitting the data to the database. make sure that you have changed the directory to your Django Project.
1 |
python manage.py runserver |
http://localhost:8000/
Subscribe and Get Free Video Courses & Articles in your Email