Kerangka pesan¶
Quite commonly in web applications, you need to display a one-time notification message (also known as “flash message”) to the user after processing a form or some other types of user input.
For this, Django provides full support for cookie- and session-based
messaging, for both anonymous and authenticated users. The messages framework
allows you to temporarily store messages in one request and retrieve them for
display in a subsequent request (usually the next one). Every message is
tagged with a specific level
that determines its priority (e.g., info
,
warning
, or error
).
Mengadakan pesan¶
Messages are implemented through a middleware class and corresponding context processor.
Awalan settings.py
dibuat oleh django-admin startproject
sudah mengandung semua pengaturan dibutuhkan untuk mengadakan pesan fungsionalitas:
'django.contrib.messages'
diINSTALLED_APPS
.MIDDLEWARE
mengandung'django.contrib.sessions.middleware.SessionMiddleware'
dan'django.contrib.messages.middleware.MessageMiddleware'
.The default storage backend relies on sessions. That’s why
SessionMiddleware
must be enabled and appear beforeMessageMiddleware
inMIDDLEWARE
.Pilihan
'context_processors'
dari backendDjangoTemplates
ditentukan di pengaturanTEMPLATES
anda mengandung'django.contrib.messages.context_processors.messages'
.
If you don’t want to use messages, you can remove
'django.contrib.messages'
from your INSTALLED_APPS
, the
MessageMiddleware
line from MIDDLEWARE
, and the messages
context processor from TEMPLATES
.
Konfigurasi mesin pesan¶
Backend Penyimpanan¶
Kerangka kerja pesan-pesan dapat menggunakan backend berbeda untuk menyimpan pesan-pesan sementara.
Django menyediakan kelas-kelas penyimpanan siap-pakai di django.contrib.messages
:
-
class
storage.session.
SessionStorage
¶ This class stores all messages inside of the request’s session. Therefore it requires Django’s
contrib.sessions
application.
Kelas ini menyimpan data pesan dalam sebuah kue (ditandai dengan campuran rahasia untuk mencegah perubahan) untuk bertahan pemberitahuan terhadap permintaan. Pesan-pesan lama dibuang jika ukuran data kue akan melebihi 2048 byte.
-
class
storage.fallback.
FallbackStorage
¶ This class first uses
CookieStorage
, and falls back to usingSessionStorage
for the messages that could not fit in a single cookie. It also requires Django’scontrib.sessions
application.Perilaku ini menghindari menulis ke sesi bilamana memungkinkan. Itu harus menyediakan penampilan terbaik di kasus umum.
FallbackStorage
adalah kelas penyimpanan awalan. Jika itu tidak cocok pada kebutuhan anda, anda dapat memilih kelas penyimpanan lain dengan mengatur MESSAGE_STORAGE
ke jalur impor penuhnya, sebagai contoh:
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
-
class
storage.base.
BaseStorage
¶
Untuk menulis kelas penyimpanan sendiri, subkelas kelas BaseStorage
di django.contrib.messages.storage.base
dan menerapkan metode _get
dan _store
.
Tingkatan pesan¶
The messages framework is based on a configurable level architecture similar to that of the Python logging module. Message levels allow you to group messages by type so they can be filtered or displayed differently in views and templates.
Tingkat siap-pakai, yang dapat diimpor dari django.contrib.messages
secar langsung, adalah:
Ketetapan |
Maksud |
---|---|
DEBUG |
Development-related messages that will be ignored (or removed) in a production deployment |
INFO |
Pesan informasi untuk pengguna |
|
Sebuah tindakan telah berhasil, sebagai contoh “Profil anda telah berhasil diperbaharui”. |
|
Kegagalan tidak muncul tetapi mungkin sebentar lagi |
|
Sebuah tindakan tidak berhasil atau beberapa kegagalan lain muncul |
The MESSAGE_LEVEL
setting can be used to change the minimum recorded level
(or it can be changed per request). Attempts to add messages of a level less
than this will be ignored.
Etiket pesan¶
Message tags are a string representation of the message level plus any extra tags that were added directly in the view (see Adding extra message tags below for more details). Tags are stored in a string and are separated by spaces. Typically, message tags are used as CSS classes to customize message style based on message type. By default, each level has a single tag that’s a lowercase version of its own constant:
Tingkat Ketetapan |
Etiket |
---|---|
DEBUG |
debug |
INFO |
info |
|
|
|
|
|
|
To change the default tags for a message level (either built-in or custom),
set the MESSAGE_TAGS
setting to a dictionary containing the levels
you wish to change. As this extends the default tags, you only need to provide
tags for the levels you wish to override:
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.INFO: '',
50: 'critical',
}
Menggunakan pesan di tampilan dan cetakan¶
Menambahkan pesan¶
Untuk menambahkan pesan, panggil:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
Some shortcut methods provide a standard way to add messages with commonly used tags (which are usually represented as HTML classes for the message):
messages.debug(request, '%s SQL statements were executed.' % count)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')
Menampilkan pesan¶
Di cetakan anda, gunakan sesuatu seperti:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
If you’re using the context processor, your template should be rendered with a
RequestContext
. Otherwise, ensure messages
is available to
the template context.
Even if you know there is only just one message, you should still iterate over
the messages
sequence, because otherwise the message storage will not be cleared
for the next request.
The context processor also provides a DEFAULT_MESSAGE_LEVELS
variable which
is a mapping of the message level names to their numeric value:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
Diluar Cetakan, anda dapat menggunakan get_messages()
:
from django.contrib.messages import get_messages
storage = get_messages(request)
for message in storage:
do_something_with_the_message(message)
For instance, you can fetch all the messages to return them in a
JSONResponseMixin instead of a
TemplateResponseMixin
.
get_messages()
akan mengembalikan sebuah instance dari backend penyimpanan dikonfigurasi
Kelas Message
¶
-
class
storage.base.
Message
¶ When you loop over the list of messages in a template, what you get are instances of the
Message
class. It’s quite a simple object, with only a few attributes:message
: Teks sebenarnya dari pesan.level
: An integer describing the type of the message (see the message levels section above).tags
: A string combining all the message’s tags (extra_tags
andlevel_tag
) separated by spaces.extra_tags
: A string containing custom tags for this message, separated by spaces. It’s empty by default.level_tag
: The string representation of the level. By default, it’s the lowercase version of the name of the associated constant, but this can be changed if you need by using theMESSAGE_TAGS
setting.
Membuat penyesuaian tingkatan pesan¶
Messages levels are nothing more than integers, so you can define your own level constants and use them to create more customized user feedback, e.g.:
CRITICAL = 50
def my_view(request):
messages.add_message(request, CRITICAL, 'A serious error occurred.')
When creating custom message levels you should be careful to avoid overloading existing levels. The values for the built-in levels are:
Tingkat Ketetapan |
Nilai |
---|---|
DEBUG |
10 |
INFO |
20 |
|
25 |
|
30 |
|
40 |
If you need to identify the custom levels in your HTML or CSS, you need to
provide a mapping via the MESSAGE_TAGS
setting.
Catatan
Jika anda sedang membuat aplikasi digunakan kembali, itu sangat dianjurkan untuk menggunakan hanya message levels siap-pakai dan jangan bergantung pada penyesuaian tingkat apapun
Merubah tingkat terekam minimal per-permintaan¶
Tingkat terekam minimal dapat disetel per permintaan melalui metode set_level
:
from django.contrib import messages
# Change the messages level to ensure the debug message is added.
messages.set_level(request, messages.DEBUG)
messages.debug(request, 'Test message...')
# In another request, record only messages with a level of WARNING and higher
messages.set_level(request, messages.WARNING)
messages.success(request, 'Your profile was updated.') # ignored
messages.warning(request, 'Your account is about to expire.') # recorded
# Set the messages level back to default.
messages.set_level(request, None)
Mirip, tingkat efektif saat ini dapat diambil dengan get_level
:
from django.contrib import messages
current_level = messages.get_level(request)
Untuk informasi lebih pada bagaimana fungsi tingkat terekam minimal, lihat Message levels diatas.
Menambahkan etiket pesan tambahan¶
Untuk lebih kendali langsung melalui etiket pesan, anda dapat secara pilihan menyediakan string mengandung etiket tambahan ke apapun dari metode tambah:
messages.add_message(request, messages.INFO, 'Over 9000!', extra_tags='dragonball')
messages.error(request, 'Email box full', extra_tags='email')
Etiket tambahan ditambahkan sebelum etiket awalan untuk tingkat itu dan ruang terpisah.
Failing silently when the message framework is disabled¶
If you’re writing a reusable app (or other piece of code) and want to include
messaging functionality, but don’t want to require your users to enable it
if they don’t want to, you may pass an additional keyword argument
fail_silently=True
to any of the add_message
family of methods. For
example:
messages.add_message(
request, messages.SUCCESS, 'Profile details updated.',
fail_silently=True,
)
messages.info(request, 'Hello world.', fail_silently=True)
Catatan
Setting fail_silently=True
only hides the MessageFailure
that would
otherwise occur when the messages framework disabled and one attempts to
use one of the add_message
family of methods. It does not hide failures
that may occur for other reasons.
Menambahkan pesan-pesan di tampilan berdasarkan-kelas¶
-
class
views.
SuccessMessageMixin
¶ Menambah sebuah atribut pesan berhasil pada
FormView
berdasarkan kelas-kelas-
get_success_message
(cleaned_data)¶ cleaned_data
adalah data dibersihkan dari formulir yang digunakan untuk pembentukan string
-
Contoh views.py:
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.edit import CreateView
from myapp.models import Author
class AuthorCreate(SuccessMessageMixin, CreateView):
model = Author
success_url = '/success/'
success_message = "%(name)s was created successfully"
The cleaned data from the form
is available for string interpolation using
the %(field_name)s
syntax. For ModelForms, if you need access to fields
from the saved object
override the
get_success_message()
method.
Contoh views.py untuk ModelForms:
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.edit import CreateView
from myapp.models import ComplicatedModel
class ComplicatedCreate(SuccessMessageMixin, CreateView):
model = ComplicatedModel
success_url = '/success/'
success_message = "%(calculated_field)s was created successfully"
def get_success_message(self, cleaned_data):
return self.success_message % dict(
cleaned_data,
calculated_field=self.object.calculated_field,
)
Pesan berakhir¶
The messages are marked to be cleared when the storage instance is iterated (and cleared when the response is processed).
Untuk menghindari pesan-pesan sedang dibesihkan, anda dapat menyetel penyimpanan pesan-pesan menjadi False
setelah perulangan:
storage = messages.get_messages(request)
for message in storage:
do_something_with(message)
storage.used = False
Perilaku dari permintaan paralel¶
Due to the way cookies (and hence sessions) work, the behavior of any backends that make use of cookies or sessions is undefined when the same client makes multiple requests that set or get messages in parallel. For example, if a client initiates a request that creates a message in one window (or tab) and then another that fetches any uniterated messages in another window, before the first window redirects, the message may appear in the second window instead of the first window where it may be expected.
In short, when multiple simultaneous requests from the same client are involved, messages are not guaranteed to be delivered to the same window that created them nor, in some cases, at all. Note that this is typically not a problem in most applications and will become a non-issue in HTML5, where each window/tab will have its own browsing context.