Every time I upload a post, it will post a row with null values inside all of the columns except the date and id, and then add a second row with the correct information put in each column. The SQLite data looks like this. Using SQL-alchemy, flask-login, wtf-forms, flask-bootstrap,werkzeug.
id title content posting_user date_posted
1 null null jack 2021-11-01
2 adad test jack 2021-11-01
Post Model
class Posts(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
content = db.Column(db.Text)
posting_user = db.Column(db.String(255))
date_posted = db.Column(db.String(50))
class Postform(FlaskForm):
title = StringField('Title', validators=[InputRequired(), Length(min = 3, max = 50)])
content = StringField('Content', validators=[InputRequired()], widget=TextArea())
HTML block
<div class="container">
<div class="row">
<div class="col-md-4 offset-md-4">
<div class="login-form bg-light mt-4 p-4">
<form action="" method="POST" class="row g-3">
<h4>Add a Post</h4>
{{ form.hidden_tag()}}
{{ form.title(placeholder = "Title") }}
{{ form.content(cols="30", rows="15", placeholder = "Write your review here") }}
<div class="col-12">
<button type="submit" name = "post_submit" class="btn btn-dark float-end">Post</button>
</div>
</form>
</div>
</div>
</div>
</div>
app.py
@app.route('/dashboard/post', methods = ["POST", "GET"])
@login_required
def post():
form = Postform()
posting = Posts(title = form.title.data, content = form.content.data, posting_user = current_user.username, date_posted = datetime.datetime.now().date())
if posting.title != None and posting.content != None:
db.session.add(posting)
db.session.commit()
flash('Your post has been added', 'posted')
return render_template("post.html", form = form, loggedin = current_user.is_active)
CodePudding user response:
It is possible that you send a GET request before your POST request in which the form is still empty. You can differentiate between the request methods to control the behavior.
@app.route('/dashboard/post', methods = ["POST", "GET"])
@login_required
def post():
form = Postform()
# Validate whether the request method is post and the entries are correct!
if form.validate_on_submit():
posting = Posts(title = form.title.data, content = form.content.data, posting_user = current_user.username, date_posted = datetime.datetime.now().date())
db.session.add(posting)
db.session.commit()
flash('Your post has been added', 'posted')
return render_template("post.html", form = form, loggedin = current_user.is_active)