Issue
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.
models.py
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"))
init.py
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
routes.py
from files import app, db
from flask import render_template
from files.models import Article
from files.forms import RegisterForm, LoginForm
@app.route('/')
@app.route('/main')
@app.route('/home')
def home():
return render_template("home.html")
@app.route('/articles/<article_name>') # dynamic route
def article(article_name):
db.create_all()
article_ = Article(title = article_name, article_content = "article", abstract = "ndng")
db.session.add(article_)
db.session.commit()
return render_template("article.html", article_name=article_name)
@app.route('/articles')
def articles():
return render_template("articles.html")
@app.route('/register')
def register():
form = RegisterForm()
return render_template("register.html", form = form)
@app.route('/login')
def login():
form = LoginForm()
return render_template("login.html", form = form)
Solution
Downgrading SQLAlchemy to anything lower than 1.4.0 (1.3.8 in my case) solves the problem.
Answered By - aras edeş
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.