Django从提交的表单中发送成功消息

7gcisfzg  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(145)

我已经启动并运行了“信息”;我可以得到一个简单的“submission successful”消息,这样我就知道context_processors和中间件都配置正确了。
下面是我的views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from menu.models import Book
from .forms import AddBook
from nextbook.models import Book
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.edit import CreateView

def library(request):
    form = AddBook(request.POST or None)
    success = False
    if request.method == 'POST':
        if form.is_valid():
            addedbook = form.save(commit=False)
            addedbook.save()
            form = AddBook()
            success = True
            messages.success(request, 'Book addition successful')

    return render(request, 'newbook/index.html', {'form': form})

class BookAddConf(SuccessMessageMixin, CreateView):
    model = Book
    success_message = "%(new_title)s by %(new_author)s was added to your library"

    def get_success_message(self, cleaned_data):
        return self.success_message % dict(
            cleaned_data,
            new_title=self.object.title,
            new_author=self.object.author
        )

我试图让success_message在用户提交表单时显示,用他们输入的数据填充消息。我在SO上读了十几个答案,但似乎找不到正确的信息来连接最后几个点。
以下是我的模板:

{% if messages %}
  <ul class="messages">
      {% for message in messages %}
      <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
      {% endfor %}
  </ul>
  {% endif %}

我知道我错过了什么,但我不确定是什么。

bhmjp9jg

bhmjp9jg1#

试试这个:

{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li {% if message.tags %} class="{{message.tags}}" {% endif %}>
    <i class="bi bi-exclamation-triangle-fill"></i>
    {{ message }}
  </li>
  {% endfor %}
</ul>
{% endif %}

相关问题