Django Messages

Django Framework

Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front and back end. The Django Software Foundation maintains the Django framework. The framework is mainly known for the pluggability of its components; that is, its components can fit into any web application. Django uses the reusability of its components method; it is also known as the DRY (Don’t  Repeat Yourself ). Django also provides read, delete and update interfaces which can be used during the runtime of the process and these can be used dynamically. Many websites use the Django framework to create their web applications; some of them include:

  • Instagram
  • Mozilla
  • Clubhouse
  • Nextdoor

Django first came into work in 2003, when two scientists, Adrian Holovaty and Simon Willison, used the python libraries to create the web application. The Django was named after Django Reinhardt, who was a guitarist. In the year 2008, the Django Software Foundation was established, which will now maintain all the properties of Django. The Django follows the MVT ( Model View template ) design pattern:

  1. Model:
    The model collects the data from the databases and provides it to the user. SQL is mainly used to extract the data from the databases, but to use SQL, we need to have a greater command of the database structure. In Django, the method the data is delivered to the user with a technique is known as Object Relational Mapping (ORM) technique which is designed mainly to make the work easier. The models are located in the file models.py
  2. View:
    The view is a kind of function that takes the HTTP requests as an argument, and with this, it will import the required models for the process and return the data to the template, which will return the final result. The view is generally located in the file views.py
  3. Template:
    The templates are generally used to present the final result of the web application. The templates generally use the .html language to design the webpage layout; we can also use the other standard file formats. The templates of the file are usually located in the folder templates.

Django Messages

Django provides the built-in messages framework, which is used to display the one-time notifications or the flash messages both to the anonymous user and the authenticated user after the completion of the process. The messages are generally displayed during login/logout requests.

We need to follow certain steps to display the message using Django:

  1. Check whether the setting is configured properly.
  2. Adding a message to the view function.
  3. Finally, we need to display the message in the template.

 First, we need to open the settings, and then we need to check whether the Django messages are added to the settings or not

Command:

My computer > my website >Settings.py
Apps = [
     ….
    ‘django.contrib.messages’,
     ….
]
MIDDLEWARE =[
                  …..
                  ‘django.contrib.sessions.middleware.SessionMiddleware’,
	       …..
                  ‘django.contrib.sessions.middleware.SessionMiddleware’,
           ….
       ],
TEMPLATES=[
            …
    ‘data_processors’: [
                              …
                              ‘django.contib.messages.data_proceesors.messages’,
                           ],
                    …

Here we can observe that the app will provide the default tags, middleware is used to call the message before or after the running of the view function, and the data processors allow the messages to be called within any template without a defined context in view.py.

Message.tags in Django:

Now we can add the tags to the messages that are, for which operation which message must be displayed can be known with the help of these Django message tags:

messages.debug( request,  ‘%s SQL statements in your command are executed.’ %count ) 

messages.info( request, ‘ Five credits are remaining in the account.’ )

messages.success( request, ' Your profile is successfully registered' )

messages.warning( request, ' The account will be expired in five days )

messages.error( request, ‘ An error has occurred while processing ’ )

The Django consists of five message tags by default: debug, info, success, warning and error. The Django message tags will be called inside the view function. We need not store these tags inside the settings.py file; it can be done with the help of Bootstrap. The Django message tags are assigned with custom CSS attributes. We need to import the Django messages into the view function, and then we can observe the result through the template file.

Importing Django Messages into View Function

We need to use the Django tags in the Djangoview.py file after creating the tags. First, we need to add the success message from the message tags to the Django view function.

Adding Django success message:

fromDjango.shortcuts import render, redirect
from .forms import ContactForm
fromDjango.core.mail import send_mail,  BadHeaderError
fromDjango.HTTP import HttpResponse
fromDjango.contrib import messages    #this command is used to import message
# This command is used to create the views.
def contact( request ):
ifrequest.method  == ‘ANNOUNCE’:
form = ContactForm(request.ANNOUNCE)
ifform.is_valid( ):
subject = “Website Checking”
body = {
                   ‘fst_name’ :form.cleanes_data[‘ fst_name ’],
                    ‘lst_name’ :form.cleaned_data[‘ lst_name ’]
	‘mail’: form.cleaned_data[ ‘mail_address’]
	‘message’: form.cleaned_data[‘ message’ ]’
}
message  =  “\n”. join(body.values( ))


try: 
mail_sent(subject, message, ‘admin@example.com’,  [‘admin@example.com’])
except  BadHeaderError:
return  HttpResponse(‘ The Header is invalid ‘)
messages.success( request, “ Message sent successfully”)
return redirect (“ main: homepage”)


fromContactForm( )
return render(requests, “main/contact.html”, {‘form’: form})

 Here, we can observe that the success message will be displayed on the main home page; to get this, first, we need to import the messages from the Django.contrib into the view function. The success message is added just before the return function statin the “Message sent”.

Adding Django error message:

fromDjango.shortcuts import render, redirect
from .forms import ContactForm
fromDjango.core.mail import send_mail,  BadHeaderError
fromDjango.HTTP import HttpResponse
fromDjango.contrib import messages    #this command is used to import message
# This command is used to create the views.
def contact( request ):
ifrequest.method  == ‘ANNOUNCE’:
form = ContactForm(request.ANNOUNCE)
ifform.is_valid( ):
subject = “Website Checking”
body = {
                   ‘fst_name’ :form.cleanes_data[‘ fst_name ’],
                    ‘lst_name’ :form.cleaned_data[‘ lst_name ’]
	‘mail’: form.cleaned_data[ ‘mail_address’]
	‘message’: form.cleaned_data[‘ message’ ]’
}
message  =  “\n”. join(body.values( ))


try: 
mail_sent(subject, message, ‘admin@example.com’,  [‘admin@example.com’])
except  BadHeaderError:
return  HttpResponse(‘ The Header is invalid ‘)
messages.success( request, “ Message sent successfully”)
return redirect (“ main: homepage”)
messages.error(request, “Error has occurred . Message not sent”)


fromContactForm( )
return render(requests, “main/contact.html”, {‘form’: form})

Here, we can observe that the error message has been added after the return function stating an error has occurred and the message is not sent. We need to add our messages to the template with the HTML code.

Adding Django messages to the template using HTML Code:

We can add the HTML file directly to the template or write some sets of code in the template function to import the HTML now into the template. The template displays the messages to the anonymous user and the authenticated user.

Creating an HTML template:

{ % if messages %}
<ul class = “messages”>
               {% for message in messages %
<li {% if message.tags %}   class = “{{message.tags }} “{% endif %}>                                       {{message}}    </li>
              {% end for %}
</ul>
{% endif %}

First, we need to go to the includes folder and then we need to create a new file known as messages.html. This folder must include the code which must be added to our template. Generally, if we use the code for more than one template, we must create the file compulsorily.

Adding messages in header.html      

<!DOCUMENT TYPE    html>
<HTML >
<head>
….
</head>
<body>


{% include ‘main/includes.messages.html’ %}


…..
</body>
</html>

To perform this operation, first, we need to go to the header.html that we created and include message.html using the Django template language. Finally, when we submit the form, we will be redirected to the homepage, and the message will be sent to the authenticated user and the authorized user that "Message sent."

Django Messages

Django with Bootstrap:

Bootstrap with Django displays different alert messages; Bootstrap will provide different colours to the additional alert messages. Bootstrap is used to display additional messages with different colours. Generally, the Blue colour is used for the primary message, the ash colour is used for the secondary alert message, the green colour is used for displaying the success message, and the red is used to display the danger message. The yellow colour is used to display the simple warning message. In this, Bootstrap provides different colours for the various template messages.


Related Topics

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

Django Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

Django Stack

Django is a popular Python web application framework that adheres to the "batteries-included" tenet. Batteries-guiding included idea is that common functionality for creating web applications should be provided with the...

5 minutes read.

Django DRF

Django Rest Framework, which is also referred to as DRF, is a very powerful application to build RESTful APIs in a Django application. DRF uses the Django framework. Similar to...

3 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Django Model

Django Model A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are...

6 minutes read.

Django Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

Django and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django. What is Django? Django is a free and open-source web...

6 minutes read.

Django Forms

Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison. It...

3 minutes read.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.