A
A
Alex_js2021-01-30 15:56:25
Flask
Alex_js, 2021-01-30 15:56:25

Why are wtforms validators not working on the second form on the page?

I want to add flask wtfroms forms to page 2. To do this, I created special classes describing them.

class UpdateAvatarForm(FlaskForm):
    avatar = FileField('Выберите файл', validators=[FileAllowed(['jpg', 'png', 'jpeg'], 'Только картинки!!'), FileRequired('Файл не выбран') ])
    submit2 = SubmitField('Загрузить')


class AddPostForm(FlaskForm):
    text = TextAreaField('Введите текст поста', validators=[DataRequired(), Length(min=10, max=500, message='Минимум 10, максимум 140 символов')])
    postimg = FileField('Выберите файл', validators=[FileAllowed(['jpg', 'png', 'jpeg'], 'Только картинки!!'), FileRequired('Файл не выбран') ])
    submit1 = SubmitField('Запостить!')


Then I created 2 instances in the view function and rendered in the template.
The essence of the first form is to update the profile picture, and the second, to add posts. The first form works adequately. And in the second, the validator constantly swears that there is no uploaded file. Even when I select a file of the wrong format, it gives an error there is no file.

view function
@app.route('/user/<username>', methods=['POST', 'GET'])
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    form = AddPostForm()
    form_update_avatar = UpdateAvatarForm()


    if form_update_avatar.submit2.data and form_update_avatar.validate():

        file = form_update_avatar.avatar.data

        file.save(app.root_path + f'/uploads/{file.filename}')
        with open(app.root_path + f'/uploads/{file.filename}', 'rb') as img:
            img = img.read()
        current_user.update_avatar(img)
        db.session.commit()
        return redirect(url_for('user', username=current_user.username))

    if form.submit1.data and form.validate():
        post = Post(body=form.text.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Пост успешно добавлен', category='success')
        return redirect(url_for('user', username=current_user.username))

    if request.args.get('action') == 'delete':
        if request.args.get('user') and request.args.get('id'):
            if request.args.get('user') == current_user.username:
                post = Post.query.filter_by(id=request.args.get('id')).first_or_404()
                db.session.delete(post)
                db.session.commit()
                return redirect(url_for('user', username=user.username))
            return redirect(url_for('user', username=user.username))
        return redirect(url_for('user', username=user.username))

    return render_template('user.html',
                           form=form,
                           form_update_avatar=form_update_avatar,
                           menu=Menu.query.all(),
                           user=user
                           )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wispik, 2021-01-30
@Alex_js

the only difference that I see is that the working form says enctype="multipart/form-data", try to write this for the second form

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question