Flask-SQLAlchemy AttributeError: can't set attribute


I try to create a database and put an article table in routes.py’s /articles/<article_name> route but it gives me AttributeError: can’t set attribute. I looked up other sources for a solution but they seemed irrelevant. Error occurs when create_all(), add(), commit() are used.


from files import db
from datetime import datetime

class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False,unique=True)
    article_content = db.Column(db.Text)
    date = db.Column(db.DateTime,default=datetime.utcnow)
    abstract = db.Column(db.String(150))
    comments = db.relationship("Comment", backref="article", lazy = True)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_name = db.Column(db.String(30), unique=True, nullable=False)
    password = db.Column(db.String(30), nullable=False)
    comments = db.relationship("Comment", backref="user", lazy = True)

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_comment = db.Column(db.String(200), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    article_id = db.Column(db.Integer, db.ForeignKey("article.id"))


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = ''
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)

from files import routes


from files import app, db
from flask import render_template
from files.models import Article
from files.forms import RegisterForm, LoginForm

def home():
    return render_template("home.html")

@app.route('/articles/<article_name>') # dynamic route
def article(article_name):

    article_ = Article(title = article_name, article_content = "article", abstract = "ndng")

    return render_template("article.html", article_name=article_name)

def articles():
    return render_template("articles.html")

def register():
    form = RegisterForm()
    return render_template("register.html", form = form)

def login():
    form = LoginForm()
    return render_template("login.html", form = form)


Downgrading SQLAlchemy to anything lower than 1.4.0 (1.3.8 in my case) solves the problem.

Answered By – aras edeş

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published