Soricidae
Soricidae

Reputation: 29

How do I pass multiple variables from one handler to another in GAE?

I want to redirect users to a confirmation page that will display both subject and content (if there is any) if they enter a valid subject, but stay on the same page and display an error if the subject is either blank or over three hundred characters.

Here is my backend code:

def post(self):
    subject = self.request.get('subject')
    content = self.request.get('content')
    a, b = self.validSubject(subject)
    if a == True and b == True:
        self.redirect('/confirm')
    else:
        if a == False:
            error = "Title cannot be blank!"
        if b == False:
            error = "Title cannot be over 300 characters."
        self.render("newpost.html", subject = subject, content = content, error = error)

Here is the code for the newpost.html template:

    <h2>New Question</h2>
    <hr>
    <form method="post">
  <label>
    <div>Title</div>
    <input type="text" id="subject" name="subject">
  </label>

  <label>
    <div>
    <textarea name="content" id="postcontent"></textarea>
    </div>
  </label>

  <b><div class="error">{{error}}</div></b>

    <input type="submit">
    </form>

I've tried adding action="/confirm" to the POST form, but that redirects to /confirm even if there is an error. I've looked at the webapp2 documentation but couldn't find anything on how to pass variables on a redirect. (https://webapp-improved.appspot.com/api/webapp2.html#webapp2.redirect)

I'm using webapp2 and jinja2. Thanks for any help in advance, I've been looking at this piece of code for quite a while :(

Upvotes: 1

Views: 134

Answers (1)

Mike
Mike

Reputation: 1246

The pattern you're trying to write doesn't work within http, irrespective of what backend platform or language you're using. Your HTML is posting to the server and the GAE code is handling the post. At that point in the interaction, the browser has already submitted and is awaiting a response from the server. You can't stop the submission at that point since it's already happened.

You should consider validating the input in Javascript before the form is even submitted to the server. That way you can suppress the submission of the form in the first place if your data isn't valid.

Take a look at the following question to see an example of this:

JavaScript code to stop form submission

Upvotes: 1

Related Questions