unable to show custom error message in Jinja2 template

蓝咒 提交于 2020-04-30 15:46:24

问题


I'm writing a register user function in ( using Flask, Python, Jinja2) which i'm checking if a username (or email) is already present and if so shows an error to below TextField.

register code is:

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = SignupForm()
    error = None
    if form.validate_on_submit():
      user_by_name = Users.query.filter_by(username=form.username.data).first()
      user_by_email = Users.query.filter_by(email=form.email.data).first()
      if user_by_name:
        error = 'Username already taken. Choose another'
        return render_template('register.html', form=form, error = error)
      elif user_by_email:
        error = 'Email already registered. Login or register with another Email'
        return render_template('register.html', form=form, error = error)
      else:
         #Add user details to DB logic
          return redirect(url_for('index'))
    return render_template('register.html', form=form, error = error)

I have a macro defined in a file util.html

    {% macro render_field(field) %}
    <div class="control-group {% if field.errors %}error{% endif %}">
        {% if kwargs.get('label', True) %}
            {{ field.label(class="control-label") }}
        {% endif %}
        <div class="controls">
            {{ field(**kwargs) }}
            {% for error in field.errors %}
                <p class="help-block">{{ error }}</p>
            {% endfor %}
        </div>
    </div>
   {% endmacro %}

and using this macro in register.html as:

{% from "util.html" import render_field %}

{% extends "base.html" %} 

{% block content %}
    <form method="post">
        {{ form.hidden_tag() }}
        {{ render_field(form.username, label=True, class="input-xlarge", autofocus="autofocus", errors=error) }}
        {{ render_field(form.password, label=True, class="input-xlarge", autofocus="autofocus") }}
        {{ render_field(form.confirm, label=True, class="input-xlarge", autofocus="autofocus") }}
        {{ render_field(form.email, label=True, class="input-xlarge", autofocus="autofocus", errors=error) }}        

        <button class="btn" type="submit">Register</button>
    </form>
{% endblock %}

Now when i test the localhost:5000/register with duplicate username or email address it doesn't show any error at all (also doesn't add any user into DB which is okay). But when i enter any wrong email or leave any field blank it shows respective error, but not showing the error which i want to pass using register view.

Is there any Jinja2 related logic missing?

And why its showing errors related to blank field or wrong email but not which i try to pass on duplicate username etc.

Please suggest.


回答1:


Well, you doing it wrong :)

{% for error in field.errors %}
      <p class="help-block">{{ error }}</p>
{% endfor %}

This macro searches for error in respective field.errors

But you pass error context variable, which is not attached to the field.

The right way to solve this will be to add def validate_user to your form definition and check for everything in there.
If it goes wrong -> raise ValidationError(message)
See example here: WTForms documentation

With this approach, your validate_on_submit() should not return True if it is not validated.




回答2:


You can just flash the error like this sample code file: views.py

@app.route('/')
def index():
    # some checks which provided error        
    if error:
        flash(error)
    return render_template('template.html')

file template.html

{% for category, msg in get_flashed_messages(with_categories=true) %}
    <div class="category">{{ msg|safe }}</div>
{% endfor %}


来源:https://stackoverflow.com/questions/15852927/unable-to-show-custom-error-message-in-jinja2-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!