Log in New API Help About

Flask SQLAlchemy Integrity Error

1.4 KB of Python
Created 11 months ago — expires in 29 days
https://dpaste.com/G4U37EPUU
COPY TO CLIPBOARD SOFT WRAP RAW TEXT DUPLICATE DIFF
# comments form
class CommentForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    comment = TextAreaField('Comment', validators=[DataRequired()])
    submit = SubmitField('Post')

# models
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    posts = db.relationship('Post', backref='author', lazy='dynamic')

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(500))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) 
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

# route
@app.route('/personal_blog', methods = ['GET', 'POST'])
def personal_blog():
    form = CommentForm()
    if form.validate_on_submit():
        user = User(username = form.username.data, email = form.email.data)        
        post = Post(body = form.comment.data, author = user)
        db.session.add(user)
        db.session.add(post)
        db.session.commit()
        flash('Your comment is now live!')  
        return redirect(url_for('personal_blog', _anchor='translate-hover'))  
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('personal_blog.html', form = form, posts = posts)

Share: