[Django]-Render to response to a redirected url in Django

3đź‘Ť

âś…

If your success page needs a dynamic message, you need to pass it there somehow. You can either do this via GET parameters in the URL you are redirecting to – eg return HttpResponseRedirect('/success/?msg=My+success+message+here') – or by setting some values in the session, which the success view can pick up.

9đź‘Ť

The response from Daniel Roseman is potentially dangerous, opening your site to XSS vulnerabilities.

Make sure you strip html tags from whatever message is passed if you must do it this way.

A better way would be to redirect to /success/?msg=ok, and have in your view a dictionary:

{ 'ok': 'Your success message' }
👤Roger

1đź‘Ť

The best way to do what you want is:
In your view set the success message (or error message) as a dict. And use the render_to_response to display any template.

In your template you can verify if there is a message and if the message is an error message or a success message.

Some like this:
In your view:

if anyError:
   dict = {"message" : {"error" : "The error message"}}
else:
   dict = {"message" : {"success" :"The success message"}}

in your template:

   {% if message %}
      {% if message.error %}
         {{ message.error }}
      {% else %}
         {{ message.success }}
      {% endif %}
   {% endif %}

Hope i’ve helped

👤Bug

0đź‘Ť

There is no good way to do what you want. The browser submits the form, which will take the user to /submit. Once you decide whether it’s “successful”, it’s too late; the browser has already decided on it’s destination. All you can do is redirect. But, as you’re finding out, it’s going to be hard to keep your POST state when you redirect.

I would give up on this. It’s not how websites are supposed to work.

👤Chase Seibert

0đź‘Ť

I think Django does this already if you extend the generic view. On create there’s an optional argument “post_save_redirect”. This functionality is used in the automatically generated Django admin system. For example if you want a new resource, say user, you go to the url “/user/add”. After you submit it redirects you to “/user/1” with a success message “you just saved user #1”. So this is possible, but I’m still researching how to do it without extending the generic view. I’m still very new to Django and python, so looking through Django core to find how they did it is not so easy for me.

👤selfsimilar

0đź‘Ť

I would recommend to use Django message framework which is used for one-time notification messages.

https://docs.djangoproject.com/en/1.8/ref/contrib/messages/

👤radeklos

Leave a comment