Django messages not displaying message

I'm trying to use django messages to notify user if form was submitted successfully or not. But nothing pops up when I submit the form no matter what. I've gone through the views.py code and template and I don't seem to anything wrong. I've even tried changing the default messages backend storage to session yet nothing.

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

views.py:

from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirect
from django.contrib import messages
from .forms import MyUserCreationForm
import bcrypt


def register(request):
    if request.method == "POST":
        # Populate form using submitted data
        form = MyUserCreationForm(request.POST)
        if form.is_valid():
            # Clone form model
            user = form.save(commit=False)
            password = user.password

            # Validate password length
            if len(password) > 25:
                messages.error(
                    request, "PASSWORD MUST BE LESS THAN OR EQUAL TO 25 CHARACTER LENGTH")

            # Hash user password
            bytes = password.encode('utf-8')
            salt = bcrypt.gensalt()
            hash = bcrypt.hashpw(bytes, salt)

            # Save modified form to database
            user.password = hash
            user.save()
            messages.success(request, "ACCOUNT CREATED SUCCESSFULLY!")
            messages.add_message(request, messages.INFO,
                                 'Thanks for reaching out! We will be in contact soon!',
                                 extra_tags='ex-tag')
            return redirect('register')
    # Create empty form
    form = MyUserCreationForm()
    return render(request, 'register.html', {'form': form})

templates/register.html:

{% extends "layout.html" %}

{% block title %}
Testing Registration
{% endblock %}

{% load static %}
{% load crispy_forms_tags %}

{% block main %}
<div class="container p-2 px-4 p-md-3">
    <div class="container-fluid p-0" style="height: 40px;"></div>
</div>
<div class="container">
    <div class="mx-auto ">
        <form method="POST" action="/register/">
            {% csrf_token %}
            {{ form | crispy }}
            <input type="submit" value="Submit" class="btn btn-primary mb-3">
        </form>
        {% if messages %}
        {% for message in messages %}
        <div class="alert alert-danger d-flex align-items-center alert-dismissible fade show" role="alert">
            <svg class="bi flex-shrink-0 me-2" role="img" aria-label="Danger:">
                <use xlink:href="#exclamation-triangle-fill" />
            </svg>
            <div>
                {{ message }}
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        {% endfor %}
        {% endif %}
    </div>
</div>
{% endblock %}

settings.py:

"""
Django settings for setup project.

Generated by 'django-admin startproject' using Django 4.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-)9-rgl0du=62az)siilt%1qgacbtmgxt!ew97t8$&nzd1v)x53'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mysite.apps.MysiteConfig',
    'crispy_forms',
    "crispy_bootstrap5",
    "phonenumber_field",
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'setup.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'setup.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'emmanuel',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_DIRS = [

]

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# Crispy-forms template pack
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"

CRISPY_TEMPLATE_PACK = 'bootstrap5'


PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.ScryptPasswordHasher',
]

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

Documentations:

If you’re using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.

https://docs.djangoproject.com/en/4.1/ref/contrib/messages/#displaying-messages

you don't send messages or RequestContext in your context:

return render(request, 'register.html', {'form': form})

Probably it should be something like that:

return render(request, 'register.html', {'form': form, 'messages':get_messages(request)})
Back to Top