Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How do I redirect to page where form originated

Tags:

python

django

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.

like image 722
sizeight Avatar asked Dec 17 '22 19:12

sizeight


2 Answers

There are a couple of options, all with the cons and benefits ofcourse.

  1. passing the originating page withi POST/GET
  2. storing the originating page in the session (won't work with multiple tabs obviously)
  3. storing the originating page in a cookie (won't work with multiple tabs either)
  4. if it's a single page, redirect to the referrer. Doesn't seem possible in your case

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.

like image 51
Wolph Avatar answered Jan 19 '23 00:01

Wolph


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

like image 30
Tomasz Zieliński Avatar answered Jan 19 '23 00:01

Tomasz Zieliński