简体   繁体   English

Flask-WTF 未验证

[英]Flask-WTF not validating

I made a WTForms for my Flask Website however the it just wont validate.我为我的 Flask 网站制作了一个 WTForms,但它无法验证。 I have made other flask WTForms before and they all seemed to work but this one just wont work我以前制作过其他 flask WTForms,它们似乎都可以工作,但这个就是行不通

forms.py 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.')

I have done these methods before but this one is really not working and its not even giving me an error.我以前用过这些方法,但这个方法真的不起作用,甚至没有给我一个错误。

routes.py路线.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 file 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>

Hope someone can help fast THANKING u SOOO SOOO SOO MUCH IF you can find a fix希望有人能帮助快速感谢你 SOOO SOOO SOO 如果你能找到解决办法

I am not sure exactly what is causing your issue, but I think I have done a very similar thing to what you are trying to accomplish, so I can share with you what worked for me and hopefully it works for you too:我不确定到底是什么导致了您的问题,但我认为我做了与您想要完成的事情非常相似的事情,所以我可以与您分享对我有用的东西,希望它也对您有用:

My Form Validation我的表单验证

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.')

Note: I did not have an email validation, but it would follow the same form as my username validation.注意:我没有 email 验证,但它与我的用户名验证形式相同。

My routes.py我的路线.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

My relevant HTML我的相关 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>

From this I don't see many differences between are code, but there are a few that could be causing your issue.从这里我看不出代码之间有很多差异,但是有一些可能会导致您的问题。

  1. my query for user in my username_validation uses ilike which makes it case insensitive我在 username_validation 中对用户的查询使用了 ilike,这使得它不区分大小写
  2. I made data required on the username field, and just inputted the users current username as the default of the form, this meant I didn't need to check if there was data in the field, I just checked if the data matched the current username.我在用户名字段上设置了必填数据,并且只输入了用户当前用户名作为表单的默认值,这意味着我不需要检查字段中是否有数据,我只检查数据是否与当前用户名匹配.
  3. Our routes are slightly different, I just look for form.validate_on_submit(), but I imagine you are using your method for all of your forms that are working, so that's probably not where the problem is我们的路线略有不同,我只是寻找 form.validate_on_submit(),但我想你正在使用你的方法来处理所有正在工作的 forms,所以这可能不是问题所在

4.Our displaying of error messages is different 4.我们的错误信息显示不同

So you can try to input some of the methods I used into your case and see if that helps at all.因此,您可以尝试将我使用的一些方法输入到您的案例中,看看是否有帮助。 It may also be useful to know what happens when you try to submit the form, does it submit no matter what is in the fields?了解当您尝试提交表单时会发生什么也可能很有用,无论字段中的内容是什么,它都会提交吗? or does it not submit at all?还是根本不提交? that might help find where the problem is.这可能有助于找到问题所在。

I hope that helps, even just a bit, Sorry if it does not!我希望对您有所帮助,即使只是一点点,如果没有,请见谅!

You could add the novalidate property in the html Form.您可以在 html 表单中添加 novalidate 属性。 Maybe the browsers validation is blocking your own.也许浏览器验证阻止了您自己的验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM