覆盖FlaskForm.validate()不允许POST请求通过

时间:2019-06-30 11:20:12

标签: python flask wtforms

摘要

我正在尝试存储除String值之外的3个float值;但在此之前,我想通过相互检查来验证FloatFields。

它们是3个指标-良好,平均和较差,我已经包含了验证器。NumberRange位于[-1,1]中。效果很好,因此,如果我输入的范围超出范围,则默认错误消息会显示在模板中,并在-1和1之间输入

现在,在将它们添加到数据库之前,我必须验证良好,平均和较差指标是否按降序排列。

代码

FORM:

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, FloatField
from wtforms.validators import DataRequired, Length, ValidationError, NumberRange
from .models import Crop


# FORMS RENDERED TO CORRESPONDING WEB TEMPLATES IN DEFINED VIEWS

class CropForm(FlaskForm):
    crop_name = StringField("Crop Name", validators=[DataRequired(), Length(max=80)])
    good_threshold = FloatField("Good", validators=[DataRequired(), NumberRange(min=-1, max=1)])
    average_threshold = FloatField("Average", validators=[DataRequired(), NumberRange(min=-1, max=1)])
    poor_threshold = FloatField("Poor", validators=[DataRequired(), NumberRange(min=-1, max=1)])
    submit = SubmitField("Submit")

    def validate_crop_name(self, crop_name):  # IGNORE THIS
        crop = Crop.query.filter_by(crop_name=str(crop_name.data).casefold().replace(" ", "").capitalize()).first()
        if crop:
            raise ValidationError("Crop with the name already exists")

    def validate(self, *args, **kwargs):
        super(CropForm, self).validate(*args, **kwargs)
        good_input = self.good_threshold.raw_data
        average_input = self.average_threshold.raw_data
        poor_input = self.poor_threshold.raw_data
        if good_input < average_input:
            self.average_threshold.errors.append("Average cannot be more than Good Indicator")
        if good_input < poor_input:
            self.poor_threshold.errors.append("Poor cannot be more Good indicator")
        if average_input < poor_input:
            self.poor_threshold.errors.append("Poor cannot be more Average indicator")

当我删除/注释CropForm FORM中的validate()块时,我能够将未经验证的值(如Good = 0.5,Average = 0.8,Poor = 0.9)发送到db,这是我不希望的,因为它们不是降序排列

当我保持原样/取消注释时,在CropForm FORM中验证()块,发送可接受的值,如Good = 0.9,Average = 0.8,Poor = 0.5,然后我点击模板上的Submit按钮,它不在全部发送值到db

型号:

class Crop(db.Model):
    id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False)
    crop_name = db.Column(db.String, unique=True, nullable=False)
    good_threshold = db.Column(db.Float)
    average_threshold = db.Column(db.Float)
    poor_threshold = db.Column(db.Float)


    def __repr__(self):
        return f"{self.id}.{self.crop_name}"

查看:

@app.route("/crops", methods=["POST", "GET"])
    def crops():
        form = CropForm()
        if form.validate_on_submit():
            crop_info = Crop(crop_name=str(form.crop_name.data).casefold().replace(" ", "").capitalize(),
                             good_threshold=form.good_threshold.data,
                             average_threshold = form.average_threshold.data,
                             poor_threshold=form.poor_threshold.data)
            db.session.add(crop_info)
            db.session.commit()
            flash(f"Thresholds added, check record #{crop_info.id}", 'success')
            return redirect(url_for('crops'))
        records = Crop.query.order_by(Crop.id)
        return render_template('crop_thresholds.html', title="Crop Thresholds", form=form, records=records)

1 个答案:

答案 0 :(得分:0)

您可以尝试将验证函数替换为类似

def validate(self, *args, **kwargs):
    super(CropForm, self).validate(*args, **kwargs)
    good_input = self.good_threshold.raw_data
    average_input = self.average_threshold.raw_data
    poor_input = self.poor_threshold.raw_data
    all_okay = True
    if good_input < average_input:
        self.average_threshold.errors.append("Average cannot be more than Good Indicator")
        all_okay = False
    if good_input < poor_input:
        self.poor_threshold.errors.append("Poor cannot be more Good indicator")
        all_okay = False
    if average_input < poor_input:
        self.poor_threshold.errors.append("Poor cannot be more Average indicator")
        all_okay = False
    return all_okay

这个想法是,validate函数将根据返回的是True还是False来确定验证是否应该成功。因此,如果任何if语句失败,则all_okay将是False并且验证失败。否则,验证将通过,您应该可以继续输入if form.validate_on_submit():代码块