与form.validate_on_submit()有关的问题

时间:2019-09-13 21:06:08

标签: python html flask

我有一个页面,允许用户编辑其个人资料。但是我遇到一个问题,其中validate_on_submit返回false(我认为)。唯一有效的时间是上载新的用户个人资料图片。但是,如果我尝试编辑其他字段,请单击“提交”。如果我删除了图片上传部分,则“提交”按钮将开始正常工作。

这是我的代码。对不起,金额代码,但我想提供尽可能清晰的图片。如果需要更多信息,请询问。

更新:我将图片上传代码移到了自己的表单中。这使validate_on_submit可以用于我的提交按钮。

更新2:我发现最终的问题是request.files在用户未编辑个人资料图片时未返回任何内容。我只需要做一个简单的检查,看看request.files是否返回了任何内容。

userImage = request.files['fileUpload']
if userImage.filename:
    # Do stuff

型号:

class EditProfileForm(FlaskForm):
    outX1 = HiddenField()
    outY1 = HiddenField()
    outX2 = HiddenField()
    outY2 = HiddenField()
    outW = HiddenField()
    outH = HiddenField()
    first_name = StringField('First Name', validators=[DataRequired()])
    last_name = StringField('Last Name', validators=[DataRequired()])
    email = EmailField(('Email'), validators=[DataRequired(), Email()])
    job_title = StringField('Job Title', validators=[DataRequired()])
    department = StringField('Department', validators=[DataRequired()])    
    start_date = DateField("Start Date", format="%Y-%m-%d",
                           default=datetime.today,
                           validators=[DataRequired()])
    current_employee = BooleanField("Current Employee")    
    fileUpload = FileField('Employee Image',
                               validators=[FileRequired(), FileAllowed(images, 'Images only!')])
    submit = SubmitField('Update Profile')

    def __init__(self, original_email, *args, **kwargs):
        kwargs['csrf_enabled'] = False
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_email = original_email

    def validate_email(self, email):
        if email.data != self.original_email:
            employee = Employee.query.filter_by(email=self.email.data).first()
            if employee is not None:
                raise ValidationError('Please use a different email address.')

路线:

@bp.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.email)
    if form.validate_on_submit():
        current_user.email = form.email.data
        current_user.first_name = form.first_name.data
        current_user.last_name = form.last_name.data
        current_user.job_title = form.job_title.data
        current_user.department = form.department.data
        current_user.start_date = form.start_date.data
        current_user.current_employee = form.current_employee.data

        userImage = request.files['fileUpload']
        x1 = request.form.get('outX1')
        y1 = request.form.get('outY1')
        x2 = request.form.get('outX2')
        y2 = request.form.get('outY2')
        width = request.form.get('outW')
        height = request.form.get('outH')
        image_name = imageManip.cropNsave(userImage, form.email.data, x1, y1, x2, y2)
        current_user.image_name = image_name

        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('main.edit_profile'))

    elif request.method == 'GET':
        print ("LOADING PROFILE PAGE")
        form.email.data = current_user.email
        form.first_name.data = current_user.first_name
        form.last_name.data = current_user.last_name
        form.job_title.data = current_user.job_title
        form.department.data = current_user.department
        form.start_date.data = current_user.start_date
        form.current_employee.data = current_user.current_employee
        imageName = current_user.image_name
        imagePath = Config.STATIC_IMG_PATH + current_user.image_name
    return render_template('edit_profile.html', title='Edit Profile',
                           form=form,
                           imagePath=imagePath,
                           imageName=imageName)

HTML:

{% block app_content %}
    <h1>Edit Profile</h1>
    <form id="cropForm">
        <div id="overlay-container" class="popup-overlay">
            <div>
                <input class="btn btn-primary" id="cropbtn" name="crop" type="submit" value="Click to Crop!">
            </div>
            <div id="image-holder">
                <img id="output_image"/>
            </div>
        </div>
    </form>
    <div class="row">        
        <form action="" method="POST" enctype="multipart/form-data" class="form" role="form">
            <div class="col-md-4">
                {{ form.csrf_token }}
                {{ form.hidden_tag() }}
                <div class="form-group  required"><label class="control-label" for="first_name">First Name</label>
                    {{form.first_name(class="form-control")}}
                </div>
                <div class="form-group  required"><label class="control-label" for="last_name">Last Name</label>
                    {{form.last_name(class="form-control")}}
                </div>
                <div class="form-group  required"><label class="control-label" for="email">Email</label>
                    {{form.email(class="form-control")}}
                </div>

                </br>

                <div class="form-group  required"><label class="control-label" for="job_title">Job Title</label>
                    {{form.job_title(class="form-control")}}
                </div>
                <div class="form-group  required"><label class="control-label" for="department">Department</label>
                    {{form.department(class="form-control")}}
                </div>
                <div class="form-group  required"><label class="control-label" for="start_date">Start Date</label>   
                    {{form.start_date(class="form-control")}}
                </div>
                <div class="form-group"><label class="control-label" for="current_employee">Current Employee? &nbsp;&nbsp;</label>   
                    {{ form.current_employee }}
                </div> 
                {{form.submit(class="btn btn-default")}}
            </div>
        </form>
        <form>
            <div class="col-md-4">                
                <img id="imageSrc" hidden="true" src="{{ imagePath }}">
                <label class="control-label" for="employee_image">Employee Photo</label>
                <br>
                <div class="input-group mb-3">
                    <div class="input-group">
                        <label id="browsebutton" class="btn btn-default input-group-addon" for="fileUpload">
                            {{ form.fileUpload(id="fileUpload", type="file", value="") }}
                            Browse...
                        </label>
                        <input class="form-control" id="image_name" name="image_name" readonly="readonly" type="text" value=" {{imageName}}" >
                    </div>                                
                </div>
                <div>
                    <div>
                        <canvas id="myCanvas" width="360" height="450"></canvas>
                    </div>
                    <div class="cropped-image-content">
                        <img id="cropped_image"</img>
                    </div>
                </div>    
            </div>            
        </form>        
    </div>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

查看您的代码,我看不到图像周围的任何错误处理。例如,如果request.files为空会怎样?我认为,如果您使此代码更健壮,则问题将得到解决。