在Wtform中对字符串长度的验证不起作用,我尝试在post方法中使用“ if form.validate_on_submit():”,但是无论输入字段中的参数如何,它都给出值:False。
main.py
from flask import Flask, render_template, request, redirect, url_for
from forms import Article
from models import db, Library
app = Flask(__name__)
app.config["SECRET_KEY"] = "hard_string_security"
@app.route('/', methods=["GET", "POST"])
def index():
form = Article()
date_db = Library.select()
# if form.validate_on_submit():
if request.method == "POST":
db.connect()
new_article = Library(titleArticle=form.title, contentArticle=form.content)
new_article.save()
db.close()
print(form.validate_on_submit())
return redirect(url_for(".index"))
return render_template("index.html", date_db=date_db, form=form)
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, Length
class Article(FlaskForm):
title = StringField("Input title arcicle", validators=[Length(min=1, max=5),DataRequired()])
content = TextAreaField("Input content arcicle", validators=[DataRequired()])
submit = SubmitField("Submit")
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>Create Article</h2>
<form method="post" action="/">
{{ form.title.label }}{{ form.title }}<br>
{{ form.content.label }}{{ form.content }}<br>
{{ form.submit }}<br><br>
</form>
</body>
</html>