• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

How to Display Messages after Form Submit in Django and Bootstrap?

Aniruddha Chaudhari/9567/10
Django

Do you want to show a confirmation message on submitting the form in your Django website?

Let’s see if the user doesn’t provide correct information while filling the form. Do you want to show the error message as “Invalid form submission.”?

Show appropriate messages on the form submissions is very necessary.

Display messages after form submit in Django is not difficult as it seems to be. Here are the simple steps to implement a message framework for your Django website.

1. Initialize the Messages App in Django Settings

Add django.contrib.messages app entry in Django INSTALLED_APPS list in settings.py.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',  #newly added
    'django.contrib.staticfiles',
    'main',
]

If you use the messages app without registering it in installed apps, you will get an error.

name 'messages' is not defined django.

This is the very first step.

2. Set up Your Common Message HTML Template.

There can be multiple forms in your web application. It is not a good practice to write the HTML template for each form.

What we are doing here is that we will write a separate HTML template and will include it in each form or wherever needed.

Here is the simple HTML template for submission.

{% if messages %}
  {% for message in messages %}
    <div class="alert alert-dismissible alert-success">
      <button type="button" class="close" data-dismiss="alert">
      ×
      </button>
      <strong>{{message}}</strong>
    </div>
 {% endfor %}
{% endif %}

Copy the above code and save this in the new template as messages.html in your template directory.

3. Include Message Template in Django Form

If you don’t have any Django form right now, let’s, create a simple HTML form with the POST method.

Include the messages.html. You can include it anywhere you want.

<div class="container">
    {% include 'messages.html' %}
    <form method="POST">
      <fieldset>
        <legend>Form</legend>
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">
        Submit
        </button>
      </fieldset>
    </form>
</div>

In this case, I’m including it above the form. This will show the message at the top of the form after submission. If you want to display the message at the bottom of the form after submission, just include the messages.html at the bottom.

4. Set the Message on Form Submission

There are multiple message types that you can set like debug, info, success, error, and warning.

In this form submission, we are interested in setting up the success and error message.

If the form submission is valid and submitted successfully, show “Contact form submitted successfully.”

messages.success(request, 'Contact request submitted successfully.')

If the form submission is invalid, show “Invalid form submission.”

messages.error(request, 'Invalid form submission.')

You can also display the actual error so that the user can understand what has gone wrong.

messages.error(request, form.errors)

If you club these all changes, this is how a function in your views.py will look like for the contact form.

def contact_form(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Contact request submitted successfully.')
            return render(request, 'contact-form.html', {'form': ContactForm(request.GET)})
        else:
            messages.error(request, 'Invalid form submission.')
            messages.error(request, form.errors)
    else:
        form = ContactForm()
    return render(request, 'contact-form.html', {'form': form})

That’s all.

Start your Django server and Boom 😀 You are done!

Similarly, you can set the messages for Django registration and sign up. Show a logged-out message on successful logging out. Show sign-up message on successful sign-up.

5. Setting Message with Bootstrap

You can enrich your message framework with Bootstrap. You can set the different colors and formats for each type of error message.

Here is the list of alert tags in bootstrap and their corresponding colors.

bootstrap alert message colors

We can use these color formatting for different types of alert messages to show the different types of messages on the form submission. Let’s say, for valid submitting, use the success alert tag (the one with blue background), for error, use the danger alert tag (the one with red background).

You can set this mapping in settings.py. Set the message tags in the settings.py.

from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
        messages.DEBUG: 'alert-secondary',
        messages.INFO: 'alert-info',
        messages.SUCCESS: 'alert-success',
        messages.WARNING: 'alert-warning',
        messages.ERROR: 'alert-danger',
}

Now you have to update your message template in messages.html.

{% for message in messages %}
<div class="container-fluid p-0">
  <div class="alert {{ message.tags }} alert-dismissible" role="alert" >
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
    {{ message }}
  </div>
</div>
{% endfor %}

Next, you can read all the entries submitted to your Django model/form.

This is how you can display messages after form submit in Django and Bootstrap. If you find any difficulty while setting messages Django form, let’s discuss it in the comment below.

Python Interview Questions eBook

BootstrapDjango
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Papan Sarkar
    June 29, 2021 at 1:50 am

    Great stuff.

    • Reply
      Aniruddha Chaudhari
      June 29, 2021 at 11:10 pm

      Thanks, Papan. I hope you enjoy going through the other tutorials as well.

  • Reply
    Joly Biden
    November 3, 2021 at 11:29 pm

    Great work.

    • Reply
      Aniruddha Chaudhari
      December 20, 2021 at 5:26 pm

      Thank you!

  • Reply
    Raman
    February 21, 2022 at 3:42 pm

    I like your simplicity in writing. Thanks.

    • Reply
      Aniruddha Chaudhari
      February 22, 2022 at 4:08 pm

      I’m glad. Thanks, Raman!

  • Reply
    Christian
    June 19, 2022 at 2:10 pm

    Hi, thanks for the tutorial.
    Just a small typo:
    in the messages code you write

    {{message}}

    – the second tag should be a closing tag.

    • Reply
      Aniruddha Chaudhari
      June 23, 2022 at 11:18 pm

      Thanks for the correction, Christian. Fixed.

  • Reply
    Musa Adamu
    August 25, 2022 at 8:59 pm

    I am enjoying these your tutorials and how you present them. They are short, precise, and implementable. I would love to follow your other channels like Youtube and other languages pages if any. Thank you.

    • Reply
      Aniruddha Chaudhari
      August 25, 2022 at 10:34 pm

      Thank you so much, Musa! Your feedback is truly motivating. You can also subscribe to our YouTube channel.

Leave a Reply Cancel reply

Prerequisite for Django

Learn Python Basics

Django Tutorials

Why Django?

Django- Create Your First Project

Django- Adding CSS/Static Files

Django- Use/Load Static Files

Django- Create Form

Django- Create Input-Tags

Django- Display Message on Form Submit

Django- MultipleChoiceField in Form

Django- Read Model Data (order_by)

Django- Read First/Last Queryset Object

Django- Update Model Field

Django- Signals

Django- Create TextField in Form

Django- Add Model to Admin Site

Django- Customize Admin Site

Django- Understanding Model User

Django- Registration/Signup Form

Django- Form Layout with Widget-Tweaks

Django- OneToOneField in Model

Django- Foreign Key & Reverse Lookup

Django- Custom Template Filters

Django- Interactive Shell

Django- Social Login

Django- Deploy and Host [FREE] 🔥

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard