Displaying Django Messages Framework Messages

前端 未结 6 584
野趣味
野趣味 2021-01-04 07:12

I have been using the Django Messaging Framework to display messages to a user in the template.

I am outputting them to the template like this:



        
6条回答
  •  孤独总比滥情好
    2021-01-04 07:55

    A bit of a faff, but you could probably achieve this by adding a custom template context processor (cf. https://docs.djangoproject.com/en/dev/ref/templates/api/ ) -- something like

    def collect_error_messages(request):
        messages = get_messages(request)
        error_messages = [ m for m in messages if 'error' in m.tags]
        return {'error_messages': error_messages}
    

    then add that to your TEMPLATE_CONTEXT_PROCESSORS list in settings.py, and then in templates you can do:

      {% for message in error_messages %}
    • {{ message }}
    • {% endfor %}

    You could do a variation on the same to build a dict mapping error level to message, and then iterate through each dict.

提交回复
热议问题