Messages & Alerts in Django Django.How

Author avatar wrote on 31/05/2022

Resource

https://www.ordinarycoders.com/blog/article/django-messages-framework

setting.py


INSTALLED_APPS = [
    ...
    'django.contrib.messages',
    ...
]

MIDDLEWARE = [
        ...
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
        'django.contrib.messages.middleware.MessageMiddleware',
        ...
    ]

TEMPLATES = [
      ...
            'context_processors': [
                ...
                'django.contrib.messages.context_processors.messages',
            ],
       ...

 

views.py

from django.contrib import messages

when action

      try:
        send_mail(subject, message, '[email protected]', ['[email protected]']) 
      except BadHeaderError:
        return HttpResponse('Invalid header found.')
      messages.success(request, "Message sent." )
      return redirect ("main:homepage")
    messages.error(request, "Error. Message not sent.")

 

Template (New File) _messages.html

Include messages in the header.html

Django message tags

in top od setting.py

import os
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',
 }

 

CRUDgen Django CRUD generator