Django contrib 消息,不打印 Box 标签

Django contrib message, not printing the Box label

我是 Django 的新手,我构建了一个小应用程序,我想在单击按钮时显示一条消息。消息正确显示到网络应用程序,但它只显示文本,不显示颜色框(绿色表示成功,红色表示错误)。我在 DOCS 和 Whosebug 上搜索了很多,但没有找到答案。谢谢你的帮助

views.py

from django.shortcuts import render
from .forms import ClientInfo
from django.contrib import messages

def send_sms(request):
    if request.method == 'POST':
        form = ClientInfo(request.POST)
        if form.is_valid():
            try:
                sms = Client.messages.create(
                    from_="+XXXXXXXXXX",
                    body=mess,
                    to=sms_client
                )
                send = sms.sid

                messages.add_message(request, messages.SUCCESS, 'Succes! Message has been sent!')

            except:
                messages.error(request, 'Error! Message has not been sent!')

form.html

{% load crispy_forms_tags %}
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
 {% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
        {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}{% endif %}
        {{ message }}
    </li>
    {% endfor %}
</ul>
{% endif %}

<form method="post">
    {% csrf_token %}
    {{ form|crispy }}
    <br>
    <button type="submit">ENVOYER</button>
    <br>
</form>

</body>
</html>

settings.py

"""
Django settings for mysite project.

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

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

# 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 = 'zfqh)_o&z_q_=yb)adwq&0gxe-aq4%n4ae8##^=*xyo#gleho6'

# 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',
    'polls',
    'crispy_forms'
]

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 = 'mysite.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 = 'mysite.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/'
ALLOWED_HOST = ['*']

好的 - 我遗漏了一些部分,例如在 python 中导入库并触发 ajax 请求 - 如果您需要这些,请告诉我。否则,如果您坚持这种模式,您应该能够使用您的 Django 应用程序完成很多工作。

views.py:

# define behavior when requests are sent to 'send_message':
def SendMessage(request):

    # unpack request:
    status = request.POST['status']

    # set message depending on status:
    if status == True:
        message = 'Everything okay!'
    elif status == False:
        message = 'Something went wrong...'

    # pack context:
    context = json.dumps({
        'message' : message,
        'status' : status,
    })

    # return an HTTP response with context:
    return HttpResponse(context)

urls.py:

# route url to view function:
urlpatterns = [
    path('send_message/', views.SendMessage, name='send_message'),
]

模板:

// create ajax request:    
$.ajax({

    // send to url:
    url : "{% url 'send_message' %}",
    type : 'POST',

    // add data to post request:
    data : {
        'status' : // status is either true or false based on some logic
    },
    dataType    :'json',

    // this function executes if we get a succesfull response from the backend:
    success : function(context) { 

        // get the value of 'status' and 'message' that was set in the backend:
        var status = context.status
        var message = context.message

        if (status) {/* do something if status is true */ }
        else {/* do something if status is false */}
    },
});