How can I redirect after POST in Pyramid?

前端 未结 6 1531
花落未央
花落未央 2021-02-04 03:50

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 websi
6条回答
  •  梦谈多话
    2021-02-04 04:11

    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 = ''
        if 'submit' in request.POST:
            user = request.POST.get('user')
            # validate your form data
            if 
    : 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.

提交回复
热议问题