1
votes

The documentation of django says 'success' is a function of django.contrib.messages.constants but when I execute django.contrib.messages.constants.success ,error comes as module 'django.contrib.messages.constants' has no attribute 'success'

Error AttributeError at /contact module 'django.contrib.messages.constants' has no attribute 'success' Request Method: POST Request URL: http://127.0.0.1:8000/contact Django Version: 3.0.5 Exception Type: AttributeError Exception Value:
module 'django.contrib.messages.constants' has no attribute 'success' Exception Location: C:\Users\User\PycharmProjects\Django\Hello\home\views.py in contact, line 35 Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.0 Python Path:
['C:\Users\User\PycharmProjects\Django\Hello', 'C:\Users\User\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\pyzmail-1.0.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\distribute-0.7.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin']

views.py

from django.shortcuts import render, HttpResponse
from datetime import datetime
from home.models import Contact
from django.contrib.messages import constants as messages

def contact(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        phn = request.POST.get('phn')
        desc = request.POST.get('desc')
        cont = Contact(name=name,email=email,phn=phn,desc= desc,date=datetime.today())
        cont.save()
        messages.success(request, 'Your mesaage has been sent')
    return render(request, 'contact.html')

models.py

from django.db import models
class Contact(models.Model):
    name = models.CharField(max_length=122)
    email = models.CharField(max_length=122)
    phn = models.CharField(max_length=13)
    desc = models.TextField()
    date = models.DateField()


admin.py

from django.contrib import admin
from home.models import Contact

# Register your models here.
admin.site.register(Contact)

settings.py

"""
Django settings for Hello project.

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

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

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

import os
from django.contrib.messages import constants as messages

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7qn946mpab^ymy)%6lnu+xe5-0yd$qr4pwo*&fljs&!k^8curx'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'home.apps.HomeConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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 = 'Hello.urls'

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


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

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


# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'



# Addded manually
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')
]
1
Totally unrelated, but by all means use a ModelForm to validate and sanitisze your user inputs. - bruno desthuilliers

1 Answers

4
votes

You should not import django.contrib.messages.constants as messages. The success method is defined on django.contrib.messages. So you can import this without renaming it, and call the method:

from django.shortcuts import render, HttpResponse
from datetime import datetime
from home.models import Contact
from django.contrib import messages

def contact(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        phn = request.POST.get('phn')
        desc = request.POST.get('desc')
        cont = Contact(name=name,email=email,phn=phn,desc= desc,date=datetime.today())
        cont.save()
        messages.success(request, 'Your mesaage has been sent')
    return render(request, 'contact.html')

The constants module can be used if you want to specify a level yourself with a parameter, for example:

from django.contrib import messages
from django.contrib.messages import constants

def some_view(request):
    # …
    messages.add_message(request, constants.SUCCESS, 'Message')