简体   繁体   中英

Flask-wtforms doesn't recognize attached file to be uploaded in Flask app

I have a form that contain FileField to upload profile picture along with some other fields, I have FileField configured in the database to not accept NULL. when I try to update the data using this form I get an error stating that the image field doesn't accept NULL while I chosen a profile picture but it's like it's not recognizing that I have.

error I get

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: employee.image_file
[SQL: UPDATE employee SET ext_no=?, image_file=? WHERE employee.id = ?]

forms.py

class UpdateEmployeeForm(FlaskForm):
    first_name = StringField(
        "First Name", validators=[DataRequired(), Length(min=1, max=20)]
    )
    last_name = StringField(
        "Last Name", validators=[DataRequired(), Length(min=1, max=20)]
    )
    picture = FileField(
        "Update Profile Picture", validators=[FileAllowed(["jpg", "png"])]
    )
    submit = SubmitField("Update")

routes.py

@users.route("/employee/<int:employee_id>/update", methods=["GET", "POST"])
@login_required
def update_employee(employee_id):
    employee = Employee.query.get_or_404(employee_id)
    if employee.organization != current_user:
        abort(403)
    form = UpdateEmployeeForm()
    if form.validate_on_submit():
        employee.first_name = form.first_name.data
        employee.last_name = form.last_name.data
        employee.image_file = form.picture.data
        db.session.commit()
        flash("Employee data has been updated!", "success")
        return redirect(url_for("users.employees"))
    elif request.method == "GET":
        form.first_name.data = employee.first_name
        form.last_name.data = employee.last_name
    image_file = url_for("static", filename="profile_pics/" + employee.image_file)
    return render_template(
        "users/add_employee.html",
        title="Update Employee",
        form=form,
        employee=employee,
        image_file=image_file,
    )

add_employee.html

<img class="rounded-circle account-img" src="{{ image_file }}">
            <div class="form-group">
                {{ form.picture.label() }}
                {{ form.picture(class="form-control-file") }}
                {% if form.picture.errors %}
                {% for error in form.picture.errors %}
                <span class="text-danger">{{ error }}</span></br>
                {% endfor %}
                {% endif %}
            </div>

I figured it out, adding enctype="multipart/form-data" to the html file solved it

    <form method="POST" action="" enctype="multipart/form-data">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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