Fefe
Fefe

Reputation: 13

Django not showing messages after redirect

I'm using Django 4.0.9, and I'm trying to show a message using django-messages after a user has been created and after it has been deleted.

Using prints I can see that the messages get created when the create/delete form executes, but when the messages are printed after the redirect to the homepage they don't exist in the Django system anymore.

The interesting part is that if I set the setting DEBUG = True to my 'settings.py' everything works as intended, if DEBUG = False I get the error mentioned above. I'm not sure if the DEBUG setting deletes the cache, doesn't take the messages after the redirect or anything of that kind.

This is my view when the user is deleted:

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.contrib import messages
from .models import User
from .forms import DeleteUser


def delete_user_view(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            form = DeleteUser(request.POST)

            if form.is_valid():
                if request.POST["delete_checkbox"]:
                    rem = User.objects.get(username=request.user)
                    if rem is not None:
                        rem.delete()
                        logout(request)
                        messages.info(request, "Il tuo account è stato cancellato.")

                        # This is the print that let's me see the messages BEFORE the redirect
                        allMsg = messages.get_messages(request)
                        print('---------------- START MSG DELETE USER ----------------')
                        if allMsg:
                            for msg in allMsg:
                                print(msg)
                                print(msg.level)

                        else:
                            print("NO MSGs!!!!")

                        print('---------------- END MSG DELETE USER ----------------')

                        return redirect('/')
                    else:
                        messages.info(request, "Spiacenti, si è verificato un errore.")
        else:
            form = DeleteUser()
        context = {'form': form}
        return render(request, 'account/delete.html', context)

The create user function is the base django one, as I'm using allauth I use an allauth signal, to run a function when a user is created:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _
from django.dispatch import receiver
from django.contrib import messages
from allauth.account.signals import user_signed_up

class User(AbstractUser):
    class Meta:
        db_table = 'auth_user'

@receiver(user_signed_up)
def user_signed_up_callback(sender, request, user, **kwargs):
    print('ESTOY POR ENVIAR MENSAJITOSS')
    messages.add_message(request, messages.INFO, "Hello world.")
    messages.add_message(request, messages.SUCCESS, _('Grazie per esserti registrato, controlla la tua mail per confermare il tuo account!'))

    # # This is the print that let's me see the messages BEFORE the redirect
    allMsg = messages.get_messages(request)
    print('---------------- START MSG DAL MODELLO USER ----------------')
    if allMsg:
        for msg in allMsg:
            print(msg)
            print(msg.level)

    else:
        print("NO MSGs!!!!")

    print('---------------- END MSG DAL MODELLO USER ----------------')
    # return messages.success(request, _('Grazie per esserti registrato, controlla la tua mail per confermare il tuo account!'))

This my requirements file:

anyascii==0.3.1
asgiref==3.6.0
beautifulsoup4==4.9.3
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==3.0.1
click==8.1.3
cryptography==39.0.0
defusedxml==0.7.1
Django==4.0.9
django-allauth==0.52.0
django-filter==22.1
django-modelcluster==6.0
django-permissionedforms==0.1
django-rosetta==0.9.8
django-taggit==3.1.0
django-treebeard==4.6.0
djangorestframework==3.14.0
draftjs-exporter==2.1.7
et-xmlfile==1.1.0
html5lib==1.1
idna==3.4
joblib==1.2.0
l18n==2021.3
nltk==3.8.1
numpy==1.24.1
oauthlib==3.2.2
openpyxl==3.1.0
pandas==1.5.3
Pillow==9.4.0
polib==1.1.1
psycopg2==2.9.5
psycopg2-binary==2.9.5
pycparser==2.21
PyJWT==2.6.0
python-dateutil==2.8.2
python3-openid==3.2.0
pytz==2022.7.1
regex==2022.10.31
requests==2.28.2
requests-oauthlib==1.3.1
rosetta==0.3
scipy==1.10.0
six==1.16.0
sorl-thumbnail==12.9.0
soupsieve==2.3.2.post1
sqlparse==0.4.3
tablib==3.3.0
telepath==0.3
tqdm==4.64.1
urllib3==1.26.14
wagtail==4.2
wagtail-color-panel==1.4.1
wagtailfontawesome==1.2.1
webencodings==0.5.1
Willow==1.4.1
xlrd==2.0.1
XlsxWriter==3.0.8
xlwt==1.3.0

and my settings.py:

import os

PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)

INSTALLED_APPS = [
    'home',
    'search',
    'user',
    'blog',
    'rss',
    'rosetta',
    #'wagtailorderable',
    'wagtail.contrib.forms',
    'wagtail.contrib.redirects',
    'wagtail.contrib.styleguide',
    'wagtail.embeds',
    'wagtail.sites',
    'wagtail.users',
    'wagtail.snippets',
    'wagtail.documents',
    'wagtail.images',
    'wagtail.search',
    'wagtail.admin',
    'wagtail',
    #'wagtail.images.panels',
    'wagtailfontawesome',
    'wagtail_color_panel',

    'modelcluster',
    'taggit',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.flatpages',
    'django.contrib.sites',
    "django.contrib.sitemaps",

    'wagtail.contrib.modeladmin',  # Don't repeat if it's there already
    'sorl.thumbnail',
]

SITE_ID = 1

MIDDLEWARE = [
    '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',
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'wagtail.contrib.redirects.middleware.RedirectMiddleware',
]

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(PROJECT_DIR, 'templates'),
        ],
        '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 = 'project.wsgi.application'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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

LANGUAGE_CODE = 'it'

TIME_ZONE = 'CET'

USE_I18N = True

USE_L10N = True

USE_TZ = True

def gettext_noop(s): return s
LANGUAGES = (
    ('it', gettext_noop('Italian')),
    ('en', gettext_noop('English')),
)

WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [
    ('it', "Italian"),
    ('en', "English"),
]

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
MODELTRANSLATION_DEFAULT_LANGUAGE = 'it'

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

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

STATICFILES_DIRS = [
    os.path.join(PROJECT_DIR, 'static'),
]

# ManifestStaticFilesStorage is recommended in production, to prevent outdated
# Javascript / CSS assets being served from cache (e.g. after a Wagtail upgrade).
# See https://docs.djangoproject.com/en/3.1/ref/contrib/staticfiles/#manifeststaticfilesstorage
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

ROSETTA_WSGI_AUTO_RELOAD = True



# Here I have been doing different test on the messages settings:

MESSAGE_LEVEL = message_constants.DEBUG

MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'

SESSION_COOKIE_SECURE = True

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.db.DatabaseCache",
        "LOCATION": "my_cache_table",
    }
}


try:
    from .local import *
except ImportError:
    pass

I have tried changing the settings of django-messages (MESSAGE_LEVEL, MESSAGE_STORAGE, etc) and tried setting the Django Cache.

But nothing helps, and still with DEBUG = True everything works as it should.

Upvotes: 1

Views: 205

Answers (0)

Related Questions