django 使用基于类的视图显示成功消息

csbfibhn  于 2023-01-27  发布在  Go
关注(0)|答案(6)|浏览(160)

我想在保存一行时显示一条成功消息,使用Django的消息传递框架和基于类的视图,代码如下所示,但不显示消息。
任何帮助都将不胜感激

#views.py

from django.views.generic import ListView, CreateView, UpdateView, TemplateView
from django.contrib.messages.views import SuccessMessageMixin

class CreateEmployee(SuccessMessageMixin, CreateView):
    model = Employee
    template_name = 'employees/create.html'
    form_class = frmCreate

    def get_success_url(self):
       return reverse('Employees:Create')

    def get_context_data(self, **kwargs):
        contexto = super(CreateEmployee, self).get_context_data(**kwargs)
        contexto['action'] = reverse('Employees:Create')
        return contexto

    success_message = 'Employee successful created'


#template
#create.html

<form action="{{ action }}" method="POST" role="form">
    {% csrf_token %}

    {{ form.as_p }}

    <input type="submit" value="Save" class="btn btn-success">
<form>

{% if messages %}
    <div class="col-lg-3 color03">
        <ul class="messages">
            {% for message in messages %}
                <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
            {% endfor %}
        </ul>
    </div>
{% endif %}
bvk5enib

bvk5enib1#

只需像这样使用self.request

from django.contrib import messages
messages.add_message(self.request, messages.INFO, 'Hello world.')
lymgl2op

lymgl2op2#

使用Django 2.2,根据文档here,这里是我在基于类的视图上的工作:
settings.py

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

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

TEMPLATES = [
    {
        'BACKEND': #,
        'DIRS': #,
        'APP_DIRS': #,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.messages.context_processors.messages',
          ],
     },
]

“默认存储后端依赖于会话。这就是为什么必须启用SessionMiddleware并且在MIDDLEWARE中显示在MessageMiddleware之前。
views.py

from django.contrib.messages.views import SuccessMessageMixin

class SignUpView(SuccessMessageMixin, CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('users:login')
    template_name = 'users/register.html'
    success_message = "%(username)s was created successfully"

urls.py

path(_('register/'), views.SignUpView.as_view(), name='register'),

在模板中:(使用引导类)

{% if messages %}
     {% for message in messages %}
         <div class="text-center alert alert-{{ message.tags }}">
             {{ message|safe }}
         </div>
     {% endfor %}
 {% endif %}
0x6upsns

0x6upsns3#

#Using django 3.2

#In views.py  

from django.contrib import messages
from .models import CreateEmployer
from django.views.generic import CreateView

class SignUpView(CreateView):
    model = CreateEmployer
    template_name = ‘employee/register_employee.html’
    fields = '__all__'

    # this method will enable your message to display
    # you can also use it to overwrite form data.
    def form_valid(self, form):
        messages.success(self.request, f”Account created successfully”)
        return super().form_valid(form)

#in your urls.py
from .views import SingUpView
from django.urls import path

urlpatterns = [
    path(‘register/‘, SignUpView.as_view(), name=“user-register"),
]

#in your template

 {% if messages %}
   {% for message in messages %}
     <div class="alert alert-{{message.tags}}">
       {{message}}
     </div>
   {% endfor %}
{% endif %}

#I hope this helps anyone facing same problem in the future.
gtlvzcf8

gtlvzcf84#

    • Django == 3.2.8**
    • 查看次数. py**

您需要在www.example.com文件内的CreateEmployee类中添加以下内容:-views.py file you need to add this :-

def form_valid(self):
        messages.success(self.request, f"Account created successfully")
        return HttpResponseRedirect(self.get_success_url()
  • 和*base. html在top base. html中,您需要添加以下内容:-
<div class="container">
    {% if messages %}
            {% for message in messages %}
              <div class="alert alert-{{ message.tags }}">
                {{ message|safe }}
              </div>
            {% endfor %}
          {% endif %}
    {% block content %}{% endblock content %}
  </div>

base. html类中使用bootstrap类。

bq3bfh9z

bq3bfh9z5#

你必须在www.example.com中设置消息存储settings.py

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

问候

rdlzhqv9

rdlzhqv96#

您也可以在“settings.py”中定义MESSAGE_TAGS以备将来使用。

# settings.py
from django.contrib import messages

# Django messages
MESSAGE_TAGS = {
    messages.DEBUG: 'alert-secondary',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

# views.py
from django.views.generic import ListView, CreateView, UpdateView, TemplateView
from django.contrib.messages.views import SuccessMessageMixin

class CreateEmployee(SuccessMessageMixin, CreateView):
    model = Employee
    template_name = 'employees/create.html'
    form_class = frmCreate
    success_message = 'Employee successful created'

    def get_success_url(self):
       return reverse('Employees:Create')

    def get_context_data(self, **kwargs):
        contexto = super(CreateEmployee, self).get_context_data(**kwargs)
        contexto['action'] = reverse('Employees:Create')
        return contexto

# and use in your template 'employees/create.html'
{% if messages %}
    {% for message in messages %}
        <div class="alert {{ message.tags }} alert-dismissible fade show" role="alert"
            {{ message|striptags|safe }}
            <button type="button" class="btn btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    {% endfor %}
{% endif %}

相关问题