Flask, jinja2: Is it possible to render part of a page with render_template() without affecting the rest of the page

StackOverflow https://stackoverflow.com/questions/22751741

  •  24-06-2023
  •  | 
  •  

Question

I have a home page that includes a few different forms one of which is an edit profile form. I am handling the forms with wtfforms and have a child template called edit_profile.html which renders both the original form and any errors returned by the edit_profile view function. What I am trying to do is this:

In the event that errors are returned: to render the child template edit_profile.html without disturbing the rest of the page.

At the moment there is a home page view function:

@app.route('/', methods=['GET','POST'])
def home():
  cur = g.db.execute(some_select_statement)
  data = cur.fetchall()
  some_var = some_function(data)
  ep_form = EditProfile()
  return render_template('home.html', some_var=some_var, ep_form=ep_form)

And then a function that deals with the editing of the profile:

@app.route('/edit_profile', methods=['GET', 'POST'])
def edit_profile():
  ep_form = EditProfile()
  if ep_form.validate_on_submit():
    # In here is the code that handles the new profile data
  return render_template('edit_html', ep_form=ep_form)

At the moment when an error is returned, most of the page is returned except that which draws upon 'some_var' to be rendered. I know that I can use Ajax to render the WTF error values and leave the rest of the page untouched but I was wondering if there was a way to do it with only the use of Flask and Jinja.

Était-ce utile?

La solution

If any error is encountered while processing the form data, redirect to the home endpoint with the POST data (using code 307).

@app.route('/edit_profile', methods=['GET', 'POST'])
def edit_profile():
  ep_form = EditProfile()
  if ep_form.validate_on_submit():
    # If the data is validated and good
    # In here is the code that handles the new profile data
    return render_template('edit_html', ep_form=ep_form)
  else:
    # If any errors are encountered, redirect
    # back to the home endpoint along with POST data
    # using code 307
    return redirect(url_for('home'), code=307)

Now in the home endpoint, we need to handle the POST data that might get redirected from edit_profile.

@app.route('/', methods=['GET','POST'])
def home():
  # fetch data from DB, other values
  ep_form = EditProfile()

  # We need to call validate_on_submit so that 
  # the data is validated and errors are populated
  if request.method == "POST":
    ep_form.validate_on_submit()

  return render_template('home.html', some_var=some_var, ep_form=ep_form)

In this way, home view function will have access to the form data, validate it and can show the errors.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top