Django: How do I redirect to page where form originated

前端 未结 3 1016
情话喂你
情话喂你 2021-02-10 18:27

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 origina

相关标签:
3条回答
  • 2021-02-10 19:12

    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

    0 讨论(0)
  • 2021-02-10 19:25

    Another option might be to create separate URL conf that resolve to the same view, and passing in the source view as a kwargs to the view.

    0 讨论(0)
  • 2021-02-10 19:27

    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.

    0 讨论(0)
提交回复
热议问题