How to pass information using an HTTP redirect (in Django)

后端 未结 11 878
北恋
北恋 2021-02-01 19:22

I have a view that accepts a form submission and updates a model.

After updating the model, I want to redirect to another page, and I want a message such as \"Field X su

11条回答
  •  攒了一身酷
    2021-02-01 20:26

    You can use django-flashcookie app http://bitbucket.org/offline/django-flashcookie/wiki/Home

    it can send multiple messages and have unlimited types of messages. Lets say you want one message type for warning and one for error messages, you can write

    def simple_action(request):
        ...
        request.flash['notice'] = 'Hello World'
        return HttpResponseRedirect("/")
    

    or

    def simple_action(request):
        ...
        request.flash['error'] = 'something wrong'
        return HttpResponseRedirect("/")
    

    or

    def simple_action(request):
        ...
        request.flash['notice'] = 'Hello World'
        request.flash['error'] = 'something wrong'
        return HttpResponseRedirect("/")
    

    or even

    def simple_action(request):
        ...
        request.flash['notice'] = 'Hello World'
        request.flash['notice'] = 'Hello World 2'
        request.flash['error'] = 'something wrong'
        request.flash['error'] = 'something wrong 2'
        return HttpResponseRedirect("/")
    

    and then in you template show it with

    {% for message in flash.notice %}
        {{ message }}
    {% endfor }}
    

    or

    {% for message in flash.notice %}
        {{ message }}
    {% endfor }}
    {% for message in flash.error %}
        {{ message }}
    {% endfor }}
    

提交回复
热议问题