Answer the question
In order to leave comments, you need to log in
How to curb Django messages?
Hi all!
I have a long standing issue with the output in the django messages template. I personally need them in one case, just on one page. Therefore, in the view, I set a message and a redirect:
if not available_cars:
carstoshow = None
messages.error(request, 'Ваш диапазон дат занят для данного объекта.')
return redirect('car_detail', pk=car_used_id)
{% if messages %}
<div class="alert alert-warning">
<div class="container text-center">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</div>
</div>
{% endif %}
{% if messages.тип_моих_сообщений %}
{% for message in messages.тип_моих_сообщений %}
Answer the question
In order to leave comments, you need to log in
Let's see how framework messages work.
https://github.com/django/django/blob/master/djang...
def messages(request):
return {
'messages': get_messages(request),
'DEFAULT_MESSAGE_LEVELS': DEFAULT_LEVELS,
}
...
def get_messages(request):
if hasattr(request, '_messages'):
return request._messages
else:
return []
class MessageMiddleware(MiddlewareMixin):
def process_request(self, request):
request._messages = default_storage(request)
...
def default_storage(request):
return import_string(settings.MESSAGE_STORAGE)(request)
...
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
def error(request, message, extra_tags='', fail_silently=False):
add_message(request, constants.ERROR, message, extra_tags=extra_tags,
fail_silently=fail_silently)
...
def add_message(request, level, message, extra_tags='', fail_silently=False):
if not isinstance(request, HttpRequest):
raise TypeError("add_message() argument must be an HttpRequest object, "
"not '%s'." % request.__class__.__name__)
if hasattr(request, '_messages'):
return request._messages.add(level, message, extra_tags) # *** THIS ***
if not fail_silently:
raise MessageFailure('You cannot add messages without installing '
'django.contrib.messages.middleware.MessageMiddleware')
def add(self, level, message, extra_tags=''):
if not message:
return
level = int(level)
if level < self.level:
return
# Add the message.
self.added_new = True
message = Message(level, message, extra_tags=extra_tags)
self._queued_messages.append(message)
...
def _get_level(self):
if not hasattr(self, '_level'):
self._level = getattr(settings, 'MESSAGE_LEVEL', constants.INFO)
return self._level
# settings.py
...
MY_SUPER_ERROR = 80
MESSAGE_LEVEL = MY_SUPER_ERROR
...
if not available_cars:
carstoshow = None
messages.add_message(request, settings.MY_SUPER_ERROR, 'Ваш диапазон дат занят для данного объекта.')
return redirect('car_detail', pk=car_used_id)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question