How can I redirect after POST in Pyramid?

19,914

Solution 1

Your problem is most easily solved by simply POSTing to the same URL that your form is shown at, and simply redirecting the user away from the page when the POST is successful. That way until the form is successfully submitted you do not change URLs.

If you're just dying to POST to a different URL, then you need to save the data using sessions, since you're obviously handling the form data between requests.

Typically if you want to be able to handle errors in your forms you would use a session and flash messages. To do this you simply add a location for flash messages to appear in your base template and setup session support using something like pyramid_beaker.

Assuming your home page is setup at the 'home' named-route:

from pyramid.httpexceptions import HTTPFound

def myview(request):
    user = '<default user field value>'
    if 'submit' in request.POST:
        user = request.POST.get('user')
        # validate your form data
        if <form validates successfully>:
            request.session.flash('Form was submitted successfully.')

            url = request.route_url('home') 
            return HTTPFound(location=url)
    return {
        # globals for rendering your form
        'user': user,
    }

Notice how if the form fails to validate you use the same code you did to render the form originally, and only if it is successful do you redirect. This format can also handle populating the form with the values used in the submission, and default values.

You can loop through the flash messages in your template of choice using request.session.peek_flash() and request.session.pop_flash().

route_url supports mutating the query string on the generated url as well, if you want to flag your home page view to check the session data.

You can obviously just pass everything in the query string back to the home page, but that's a pretty big security vulnerability that sessions can help protect against.

Solution 2

The Pyramid documentation has a particularly on-point section with the following example:

from pyramid.httpexceptions import HTTPFound

def myview(request):
    return HTTPFound(location='http://example.com')

Solution 3

I do this like so:

from pyramid.httpexceptions import HTTPCreated

response = HTTPCreated()
response.location = self.request.resource_url( newResource )
return response

This sends the HTTP Created code , 201

Solution 4

The Pyramid documentation has content about Redirect, you can see more information in below link :

Pyramid documentation

import pyramid.httpexceptions as exc
raise exc.HTTPFound(request.route_url("section1"))   # Redirect

Edited: Actually you can do that on client side with Javascript, first you should send particular response to client side(either with flashes some data or return Response object):

window.location = '{{ request.route_path("route_name") }}';
Share:
19,914

Related videos on Youtube

dave
Author by

dave

Updated on August 26, 2020

Comments

  • dave
    dave over 3 years

    I'm trying to have my form submit to a route which will validate the data then redirect back to the original route.

    For example:

    • User loads the page website.com/post
    • Form POSTs the data to website.com/post-save
    • User gets redirected back to website.com/post

    Pyramid is giving me some troubles doing this.

    Here's my slimmed down views.py

    def _get_link_form(post_data):
        """ Returns the initialised form object """
    
        return LinkForm(post_data)
    
    def home_page(request):
    
        form = _get_link_form(request.POST)
        return {'form' : form}
    
    def save_post(request):
        """ form data is submitted here """"
    
        form = _get_link_form(request.POST)
    
        if not form.validate():
            return home_page(request, form)
    

    This is the code I've been playing around with. Not only does it not work, it also feels messy and hacked up. Surely there's a simpler way to 'redirect after-POST' in Pyramid?

  • dave
    dave about 13 years
    Redirecting is easy. The problem is, how do I redirect back to home_page and send along the form errors found in save_post ?
  • John Flatness
    John Flatness about 13 years
    One way you could deal with this is to sort of reverse the way you're doing things now: Have home_page also be the view that the form submits to, and then do a redirect only if the submission was successful. So, if you need to display errors, home_page already has the form object it needs.
  • dave
    dave about 13 years
    I was considering that but I have two different view callables that will render the form. I could have them both submit to the one, main, view callable (home_page, in this example) but it'd be nice if each view callable could redirect back to itself after submitting - if that makes sense...
  • kkessell
    kkessell about 11 years
    Sure, but on the POST branch, when validation fails, you should generally do, what you do in GET...
  • Carlos Agarie
    Carlos Agarie over 9 years
    I think the current URL for that section is this one.
  • Piotr Dobrogost
    Piotr Dobrogost about 8 years
    There's no action decorator in Pyramid. I guess you're using action decorator from pyramid_handlers package.
  • Piotr Dobrogost
    Piotr Dobrogost about 8 years
    I think you missed the point of the question which was to submit a form using POST to a different url then the one used to GET the form. Both of your handlers are registered under the same name (save) thus they are accessible under the same url.
  • Piotr Dobrogost
    Piotr Dobrogost about 8 years
    Using HTTPFound results in HTTP response code 302 thus the next request will be GET instead of the original POST. As a consequence you won't get form's data in the home_page view because you are looking in request.POST.
  • LD Jewell
    LD Jewell about 8 years
    I'm proposing a cleaner way of acheiving their requeriments, using the same url but managing the code between 2 methods. I'm using the same approach Michael Merickel is using in other response.