首页 文章

django:messages.add_message没有显示在html页面中

提问于
浏览 1544
0

我有一个Django库应用程序,其中我有一个book_detail页面,用户可以在其中下载/通过电子邮件将该书的pdf链接发送给自己 .

发送此类电子邮件(工作正常,收到电子邮件), I want to display a pop-up or an alert message on that same html page instead of redirecting to some other page.

这是views.py代码:

def send_email(request):

try:
    send_mail('Book request', 'email body', settings.EMAIL_HOST_USER, ['xyz@gmail.com'], fail_silently=False)

    #this message is not getting displayed in the same html page
    messages.add_message(request, messages.SUCCESS, 'Email sent successfully.')

except EmailMessage:
    messages.add_message(request, messages.SUCCESS, 'Error has occurred')

HTML页面book_detail.html代码:

......
  rest of the code....

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

{% endblock %}

我使用提交按钮点击发送电子邮件:

urlpatterns = [
   path('', views.index, name='index'),
   ......
   path('email_book/', views.send_email, name='email_book'),
 ]

发生错误:

Please suggest what should be done, is there any other solution I can try for displaying an alert box/message on that same html page, without redirecting it to any other page.

谢谢!

UPDATE:

由于book_detail.html页面固有一个复杂的URL路由,因此当我在其他html页面中使用它时,会显示django消息:

def otherpage(request):
    ....
    messages.add_message(...)
    return render(request, 'other_page.html')

1 回答

  • 0

    Django中的视图函数应该总是返回一些 Response 对象

    def send_email(request):
    
      try:
        send_mail('Book request', 'email body', settings.EMAIL_HOST_USER, ['xyz@gmail.com'], fail_silently=False)
    
        #this message is not getting displayed in the same html page
        messages.add_message(request, messages.SUCCESS, 'Email sent successfully.')
    
      except smtplib.SMTPException:
        messages.add_message(request, messages.SUCCESS, 'Error has occurred')
      return render(request, 'book_detail.html', {
        'messages': messages,
      }, content_type='text/html')
    

相关问题