How to pass a message from HttpResponseRedirect in Django?

后端 未结 4 2010
夕颜
夕颜 2020-12-25 11:57

I have a view which does the certain task and return to another view which render hello.html template.

def 1stview(request):
   #Do this
   #Do that
   retur         


        
4条回答
  •  余生分开走
    2020-12-25 12:15

    Adding a more elaborative answer.

    1: Configure a message storage in your settings.py:

    MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
    

    or if you are not using sessions, use CookieStorage:

    MESSAGE_STORAGE = 'django.contrib.messages.storage.session.CookieStorage'
    

    2: In your view, import django.contrib.messages:

    from django.contrib import messages
    

    3: Set the message data before returning the HttpResonse:

    messages.success(request, 'Changes successfully saved.')
    

    which is a shorthand for:

    messages.add_message(request, messages.SUCCESS, 'Changes successfully saved.')
    

    The message tags (messages.SUCCESS in this case) can then be used in your template to i.e. add a corresponding CSS-class or hide debug-messages. Django includes a few by default but if you wish to use this with Bootstrap's default alert classes you will need to add some custom message tags for the missing ones.

    4: In your template you can then use the messages like this if you are using Bootstrap alerts:

    {% if messages %}
        {% for message in messages %}
            
        {% endfor %}
    {% endif %}
    

    For example, Django uses 'error' as the default tag for ERROR while Bootstrap uses danger to indicate errors. The best solution is to use custom tags, but you can also monkeypatch it in your template (ugly solution):

    {% if messages %}
        {% for message in messages %}
                
        {% endfor %}
    {% endif %}
    

提交回复
热议问题