In my Django app I have multiple pages displaying a link that loads a new page displaying a form. When the form is submitted, what is the cleanest way to redirect to the originating page from which this form was accessed?
originating page -> form page -> originating page
Using a next variable seems unellegant since I have to set it as a GET variable on the originating page link, and then set it as a hidden POST variable in my form? Any other ideas would be appreciated.
There are a couple of options, all with the cons and benefits ofcourse.
POST
/GET
Personally I think using a next parameter is your best option, but do remember to secure it (only relative urls, no javascript stuff, csrf framework) so you won't have any security problems with it.
WoLpH already listed the resonable possibilities and pointed to (probably) the best of them as a solution. So I will only elaborate on it.
If you need to handle this: originating page -> form page -> originating page then in reality it will look like this: originating page --[GET]--> form page --[POST/submision]--> form page(2) --[GET/redirect]--> originating page. This means, that form page(2) stage has to somehow know where to redirect user and the only reasonable choices you have here is to use session (with the drawback mentioned by WoLpH) or to pass it in POST, possibly as a hidden field.
Regarding the first GET and passing next URL
into form page, you can either pass it in the query string (which you find unelegant), or you can extract it from HTTP_REFERER header - which won't work for more paranoid users like me.
You can also do a mixed stuff here, i.e. add next=<next-URL>
into the query string if and only if user hasn't turned off HTTP_REFERER in her browser. Then most users won't see any ugly stuff in URLs.
Note that all these things can be automated, i.e. you can write your links as:
<a href="{% url myform %}?{% inject_next_url %}">
When inject_next_url
injects sth like: next={{ context['request'].get_full_path() }}
only if HTTP_REFERER is not present.
Then, in form handler you can use some generic extract_next_url(request)
function, that looks for next URL
in one of: query string, HTTP_REFERER, request.POST, or more consise - in one of: HTTP_REFERER, request.REQUEST
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With