Module 'django.contrib.messages.constants' has no attribute 'error'
I was working on my django project and everything seemed fine, until I simply wanted to login, and I found this error:
module 'django.contrib.messages.constants' has no attribute 'error'
The code that is responsible for this has not been touched for at least 2 months!
Here is the view:
from django.contrib.auth import authenticate
from django.conf.settings import *
from django.contrib import messages
# Connexion
def loginview(request):
if request.method == 'POST':
usr = request.POST.get('email_kw')
pwd = request.POST.get('pwd_kw')
user = authenticate(request, username=usr, password=pwd)
if user is not None:
login(request, user)
logger.info(f"Connexion de {request.user}")
return redirect("dashboard")
else:
messages.error(request, "Erreur: Nom d'utilisateur ou mot de passe incorrects, veuillez réessayer.") # this is the line that causes the problem
logger.error(f'Connexion de {request.user} echouee')
return render(request, 'core/login.html', {'page_title': 'Se connecter'})
if request.user.is_authenticated:
return redirect("dashboard")
return render(request, 'core/login.html', {'page_title': 'Se connecter'})
This is a very tricky problem. And the answer is simple.
Although you have imported the right component (which is django.contrib.messages
), you have also imported settings, probably to use some global variables.
The problem here is that you have imported ALL the variables and methods inside settings.py, and since you are using messages, you are for sure using bootstrap alerts, hence, you are importing the messages constants inside your settings.py (django.contrib.messages.constants
).
And in a lot of tutorials, they ask you to put this: from django.contrib.messages import constants as messages
.
Now, you have this:
from django.conf.settings import *
from django.contrib import messages
Which means, you are importing the settings before the messages, which means the messages you are using, are the constants.
To solve this you can simply rename the constants in your settings to something else rather than messages. Or, simply follow the good practices of any object oriented software engineering, and never use import *
, always only import the variables or functions you really need, and therefore, change from django.conf.settings import *
to from django.conf import settings
and use settings.YOUR_VARIABLE
, or, you can do this as well: from django.conf.settings import YOUR_VARIABLE, YOUR_METHOD