Using Flask + Flask-Classy + WTForms, I try to implement a route, so when the user has an error in their input form, the application will again submit this form to the user, complete with what the user has already filled out. Thus, the user did not have to worry about re-entering all input forms: (s) he can fix the errors.
This is the code from my UserView class (FlaskView), which is a class of checkboxes class:
def post(self): form = forms.UserForm(request.form) if form.validate(): if form.id.data=='': user = models.Users() form.populate_obj(user) user.id = None db.session.add(user) else: user = models.Users.query.get(form.id.data) form.populate_obj(user) db.session.commit() return redirect(url_for('UserView:index')) else: return redirect(url_for('UserView:validation_error', error_form=form)) def validation_error(self, error_form): return render_template('users/form.html', form=error_form)
You can see that in this attempt I am trying to create another method: validation_error , with an argument - what in my expectation - should contain all the form data. But it turns out I have a Jinja2 exception, UndefinedError: 'unicode object' has no attribute 'hidden_tag' . When I checked it, after validation_error , this form object changed somewhat from UserForm to some unicode object.
Any suggestion? Or am I trying to solve this problem in the wrong direction?
EDIT 1: more on how to display an error
As @Rawrgulmuffins added an answer on how to display an inline error (which I think is best, as the page will not get jumpy), here I pasted the code into my layout.html , which lists all the errors. It may not be as good as displaying a built-in error, but I think this is the easiest way. First I do an if for the form object, as this code also exists for all pages (I might have reorganized it even more)
{% if form %} {% for error in form.errors %} <div class="alert alert-error"> <a class="close" data-dismiss="alert">Γ</a> <strong>{{ form[error].label }} {{form.errors[error][0] }}</strong> </div> {% endfor %} {% endif %}
Screenshot:
