【问题标题】:Flask-WTF not validatingFlask-WTF 未验证
【发布时间】:2022-02-16 23:17:26
【问题描述】:

我为我的 Flask 网站制作了一个 WTForms,但它只是无法验证。我之前制作过其他烧瓶 WTForms,它们似乎都可以工作,但这个就不行了

forms.py

class UpdateForm(FlaskForm):
    picture = FileField('Update Profile Picture', validators=[FileAllowed(['jpeg', 'jpg', 'png'])])
    username = StringField("Username", validators=[], render_kw={"placeholder": f"Enter username"})
    email = StringField("Email", validators=[Email()], render_kw={"placeholder": "Enter email"})
    submit = SubmitField('Update')

    def validate_username(self, username):
        if username.data is not None:
            user = User.query.filter_by(username=username.data).first()
            if user:
                raise ValidationError('Username is already taken.')

    def validate_email(self, email):
        if email.data is not None:
            emailL = User.query.filter_by(email=email.data).first()
            if emailL:
               raise ValidationError('Email is already taken.')
            else:
                raise ValidationError('Enter a valid email.')

我以前做过这些方法,但是这个真的不起作用,甚至没有给我一个错误。

routes.py

@app.route('/settings/edit-profile', methods=['POST', 'GET'])
def edit_profile():
    if not current_user.is_authenticated:
        flash('This process requires login.', 'failure')
        return redirect(url_for('login'))
    else:
        form = UpdateForm()
        if request.method == "POST" and form.validate_on_submit():
            print(form.username.data)
            print(form.email.data)
            pfp = url_for('static', filename=f'pfplib/{current_user.pfp}')
            return render_template("Settings/edit-profile.html", pfp=pfp, form=form)
        pfp = url_for('static', filename=f'pfplib/{current_user.pfp}')
        return render_template("Settings/edit-profile.html", pfp=pfp, form=form)

html文件

<form method="POST" action="" enctype="multipart/form-data">
            {{ form.csrf_token }}
            {{ form.hidden_tag() }}
            <div class="main-content">
                <div class="pfp-change">
                    <div class="container-pfp">
                        <img src="{{ pfp }}">
                        <div class="pick-div">
                            <input type="file">
                            <i class="fa fa-camera" style="color: #ffffff"></i>
                        </div>
                    </div>
                </div>
                <div class="edit-profile-form">
                    <div class="username-column">
                        {{ form.username.label(class="head-label") }}
                        {% if form.username.errors %}
                            {{ form.username(class="string-field") }}
                            {% print(error) %}
                            <div class="invalid-feedback">
                                <span>{{ error }}</span>
                            </div>
                        {% else %}
                            {{ form.username(class="string-field", value=current_user.username) }}
                        {% endif %}
                    </div>
                    <div class="email-column">
                        {{ form.email.label(class="head-label") }}
                        {{ form.email(class="string-field", value=current_user.email) }}
                    </div>
                </div>
            </div>
            <div class="submit-div">
                {{ form.submit(class="btn-gradient submit-btn-1") }}
            </div>
        </form>

希望有人能快速提供帮助 非常感谢你,如果你能找到解决办法

【问题讨论】:

  • 使用“更新”,你到底是什么意思?是像您一样简单地获取表单中的信息,还是“更新”数据库?

标签: python python-3.x flask flask-wtforms wtforms


【解决方案1】:

我不确定究竟是什么导致了您的问题,但我认为我所做的事情与您想要完成的事情非常相似,所以我可以与您分享对我有用的东西,希望它也对您有用:

我的表单验证

class EditProfileForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    about_me = TextAreaField('About me', validators=[Length(min=0, max=250)])
    website_link = StringField('Link your website', validators=[Optional(), URL(message='This is not a valid link, make sure you enter the entire URL')])
    submit = SubmitField('Apply Changes')


    def __init__(self, original_username, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_username = original_username

    def validate_username(self, username):
        if username.data != self.original_username:
            user = User.query.filter(User.username.ilike(self.username.data)).first()
            if user is not None:
                raise ValidationError('This username is already taken')
            if ' ' in username.data:
                raise ValidationError('Your username may not contain spaces.')

注意:我没有电子邮件验证,但它与我的用户名验证形式相同。

我的路线.py

@app.route('/edit_profile/', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        current_user.website = form.website_link.data
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('main.user', username = current_user.username))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me

我的相关 HTML

<form action="" method="post">
        {{ form.hidden_tag() }}
        <p>
            <div id="changePPLink"><a href="{{ url_for('main.pic_upload') }}" >Change your profile picture</a><br></div>
            <div id="changePasswordLink"><a href="{{ url_for('auth.change_password') }}">Change your password</a><br></div>
            {{ form.username.label }}<br>
            {{ form.username(size=32, id="usernameField") }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">{{ error }}</span>
            {% endfor %}
        </p>
        <p>
            {{ form.about_me.label }}<br>
            {{ form.about_me(cols=50, rows=4, id="aboutMeField") }}<br>
            {% for error in form.about_me.errors %}
            <span style="color: red;">{{ error }}</span>
            {% endfor %}
        </p>
        <p>
            {{ form.website_link.label }}<br>
            {{ form.website_link(size=32, id="websiteField") }} <br>
            {% for error in form.website_link.errors %}
            <span style="color: red;">{{ error }}</span>
            {% endfor %}
        </p>

        <p>{{ form.submit() }}</p>

    </form>

从这里我看不出代码之间有很多差异,但有一些可能会导致您的问题。 1.我的表单中有一个 init 函数 2. 我在 username_validation 中对用户的查询使用了 il​​ike,这使得它不区分大小写 3.我在用户名字段上设置了必填数据,并且只是输入了用户当前的用户名作为表单的默认用户名,这意味着我不需要检查字段中是否有数据,我只检查数据是否匹配当前用户名。 4. 我们的路线略有不同,我只是寻找 form.validate_on_submit(),但我想你正在使用你的方法来处理所有有效的表单,所以这可能不是问题所在

5.我们的错误信息显示方式不同

因此,您可以尝试将我使用的一些方法输入到您的案例中,看看是否有帮助。 了解当您尝试提交表单时会发生什么也可能很有用,无论字段中的内容是否都提交?还是根本不提交?这可能有助于找出问题所在。

希望对你有帮助,哪怕只是一点点,如果没有,请见谅!

【讨论】:

    【解决方案2】:

    您可以在 html 表单中添加 novalidate 属性。也许浏览器验证会阻止您自己的验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2013-06-16
      相关资源
      最近更新 更多