Django小技巧14: messages 框架

Django小技巧14: messages 框架

Posted October 30, 2018

翻譯整理自: simpleisbetterthancomplex.com

讓用戶知道應用程序發生了什麼, 是個極好的用戶體驗。讓應用程序和用戶之間能夠有個很好的『交流』是個不錯的選擇。

設想一下下面場景:

  • 用戶: 點擊保存按鈕
  • 應用程序: 什麼都沒有發生
  • 所以是否保存了數據? 用戶並不知道
  • 這時一些急性子就瘋狂的點擊,點擊,點擊...

所以, 要讓用戶不要慌...

配置

默認情況下,Django 項目內置了messages框架, 如果你沒有更改這些配置, 只需要跳到下一節。 如果有改動, 按照下面這樣設置:

  • NSTALLED_APPS
    • django.contrib.messages
  • MIDDLEWARE 或者 MIDDLEWARE_CLASSES(老版本)
    • django.contrib.sessions.middleware.SessionMiddleware
    • django.contrib.messages.middleware.MessageMiddleware
  • TEMPLATES
    • context_processors
      • django.contrib.messages.context_processors.messages

消息級別和標籤

Constant

Level

Tag

Purpose

DEBUG

10

debug

開發相關的消息

INFO

20

info

用戶級別消息

SUCCESS

25

success

一個操作的成功消息

WARNING

30

warning

失敗但非迫在眉睫的消息

ERROR

40

errror

操作未成功或發生錯誤

默認情況下, Django 只會顯示 level >= 20 (INFO)的消息, 如果顯示DEBUG消息, 可以在設置中:

settings.py

Python

from django.contrib.messages import constants as message_constants
MESSAGE_LEVEL = message_constants.DEBUG

爲了避免遇到導入循環, 可以直接設置 level.

Python

MESSAGE_LEVEL = 10  # DEBUG

使用

在視圖裏面必要的地方添加, 觸發消息的邏輯, 在模板裏面添加顯示的代碼, 就可以使用消息啦

views.py

Python

from django.contrib import messages

@login_required
def password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, 'Your password was updated successfully!')  # <-
            return redirect('settings:password')
        else:
            messages.warning(request, 'Please correct the error below.')  # <-
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'profiles/change_password.html', {'form': form})

然後template中

Django/Jinja

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

如果添加成功了, 則輸出的 html 應該是這樣呢, 可以看到實際上標籤應該和你的用戶美化messsage的 css 對應。

HTML

<ul class="messages">
  <li class="success">Your password was updated successfully!</li>
</ul>

你可以對 message, 添加額外的標籤:

Python

messages.success(request, 'Your password was updated successfully!', extra_tags='alert')

輸出html 爲:

HTML

<ul class="messages">
  <li class="success alert">Your password was updated successfully!</li>
</ul>

內置方法介紹:

Python

messages.debug(request, 'Total records updated {0}'.format(count))
messages.info(request, 'Improve your profile today!')
messages.success(request, 'Your password was updated successfully!')
messages.warning(request, 'Please correct the error below.')
messages.error(request, 'An unexpected error occured.')

# Or...

messages.add_message(request, messages.DEBUG, 'Total records updated {0}'.format(count))
messages.add_message(request, messages.INFO, 'Improve your profile today!')

# Useful to define custom levels:
CRITICAL = 50
messages.add_message(request, CRITICAL, 'A very serious error ocurred.')

和Bootstrap結合代碼片段

  • messages.html

Django/Jinja

{% for message in messages %}
  <div class="alert {{ message.tags }} alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    {{ message }}
  </div>
{% endfor %}
  • settings.py

Bootstrap 中定義瞭如alert-info或者alert-successalert-*的組件css. 所以我們需要更改下默認的 tags.

Python

from django.contrib.messages import constants as messages

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}
  • base.html

然後把messages.html添加到需要顯示的地方:

Django/Jinja

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Simple is Better Than Complex</title>
  </head>
  <body>
    {% include 'partials/header.html' %}
    <main>
      <div class="container">
        {% include 'partials/messages.html' %}
        {% block content %}
        {% endblock %}
      </div>
    </main>
    {% include 'partials/footer.html' %}
  </body>
</html>

閱讀更多關於messages框架的文檔. Django Documentation

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章