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

后端 未结 11 1116
北恋
北恋 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:23

    I liked the idea of using the message framework, but the example in the django documentation doesn't work for me in the context of the question above.

    What really annoys me, is the line in the django docs:

    If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.

    which is incomprehensible to a newbie (like me) and needs to expanded upon, preferably with what those 2 options look like.

    I was only able to find solutions that required rendering with RequestContext... which doesn't answer the question above.

    I believe I've created a solution for the 2nd option below:

    Hopefully this will help someone else.

    == urls.py ==

    from django.conf.urls.defaults import *
    from views import *
    
    urlpatterns = patterns('',
        (r'^$', main_page, { 'template_name': 'main_page.html', }, 'main_page'),
        (r'^test/$', test ),
    

    == viewtest.py ==

    from django.contrib import messages
    from django.http import HttpResponseRedirect
    from django.core.urlresolvers import reverse
    
    def test(request):
        messages.success( request, 'Test successful' )
        return HttpResponseRedirect( reverse('main_page') )
    

    == viewmain.py ==

    from django.contrib.messages import get_messages
    from django.shortcuts import render_to_response
    
    def main_page(request, template_name ):
        # create dictionary of items to be passed to the template
        c = { messages': get_messages( request ) }
    
        # render page
        return render_to_response( template_name, c, )
    

    == main_page.html ==

    {% block content %}
        {% if messages %}
        
    {% for message in messages %}

    {{ message.message }}

    {% endfor %}
    {% endif %} {% endblock %}

提交回复
热议问题