How to pass a message from HttpResponseRedirect in Django?

后端 未结 4 1962
夕颜
夕颜 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 %}
            <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div>
        {% 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 %}
                <div class="alert {% if message.tags %}alert-{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}danger{% else %}{{ message.tags }}{% endif %}{% endif %}" role="alert">{{ message }}</div>
        {% endfor %}
    {% endif %}
    
    0 讨论(0)
  • 2020-12-25 12:21
    from django.contrib import messages
    messages.success(request, _('Thank you'))
    return redirect('/whatever/')
    
    0 讨论(0)
  • 2020-12-25 12:23

    Be careful when using i18n urls! If you use a link like /whatever/ but use internationalization, it will redirect to /en/whatever/, thus losing the message in the request. If you use internationalization, always pass the language to the URL:

    from django.contrib import messages
    from django.utils.translation import get_language
    
    messages.success(request, _('Thank you'))
    return redirect('/%s/whatever/' % get_language())
    

    Cost me a couple hours to understand this...

    0 讨论(0)
  • 2020-12-25 12:31

    Use the messages framework to send messages between page requests.

    0 讨论(0)
提交回复
热议问题