How do I redirect in Django with context?

前端 未结 5 1674
野的像风
野的像风 2020-11-30 03:49

I have a view that validates and saves a form. After the form is saved, I\'d like redirect back to a list_object view with a success message \"form for customer xyz was suc

5条回答
  •  不知归路
    2020-11-30 04:23

    Please note the answer suggested here is only applicable to Django < 1.2:

    Do you have control over the view that you are redirecting to? In that case you can save the context in the session before redirecting. The target view can pick up the context (and delete it) from the session and use it to render the template.

    If your only requirement is to display a message then there is a better way to do this. Your first view can create a message for the current using auth and have the second view read and delete it. Something like this:

    def save_form(request, *args, **kwargs):
        # all goes well
        message = _("form for customer xyz was successfully updated...")
        request.user.message_set.create(message = message)
        return redirect('list_view')
    
    def list_view(request, *args, **kwargs):
        # Render page
    
    # Template for list_view:
    {% for message in messages %}
       ... 
    {% endfor %}
    

    Messages are saved to the database. This means that you can access them even after a redirect. They are automatically read and deleted on rendering the template. You will have to use RequestContext for this to work.

    For Django => 1.2 read the answer involving messages

提交回复
热议问题