无法在Flask-admin上创建模型 [英] Unable to create models on Flask-admin
问题描述
我在Flask上创建了一个简单的博客,并试图实施Flask-Admin来管理我的帖子。如果我去管理区域,我可以从数据库中看到我的所有帖子的列表,但是当我尝试创建一个新的时,我得到了下一个错误:
创建模型失败。 __init __()需要正好4个参数(1给出)
这是我的博文模型:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ,primary_key = True)
title = db.Column(db.String(100))
content = db.Column(db.Text)
created_at = db.Column(db.DateTime)
def __init __(self,title,content):
self.title = title.title()
self.content = content
self.created_at = datetime。 datetime.now()
这是我将代码添加到UI的代码:
从瓶子导入烧瓶,从模型导入
导入数据库,从$ flask.ext.admin过帐
import Admin
from flask.ext.admin.contrib.sqlamodel import ModelView
$ b $ app = Flask(__ name__)
app.config ['SQLALCHEMY_DATABASE_URI'] ='mysql:// root:pass @ localhost / appname'
db.init_app(app)
$ b $ admin = Admin( app)
admin.add_view(ModelView(Post,db.session))
I DO可以通过管理面板编辑模型,但不能创建新模型。编辑:如果我不执行 init 在模型上。我怎样才能解决这个问题?
https://github.com/mrjoes/flask-admin/blob/master/flask_admin/contrib/sqlamodel/view.py#L763\">这里。 model = self.model()
$> c $ c>
所以你应该支持一个不带参数的构造函数。例如,用默认参数声明你的 __ init __
构造函数:
def __init__ (self,title =,content =):
self.title = title.title()
self.content = content
self.created_at = datetime.datetime.now )
I'm creating a simple blog on Flask and I'm trying to implement Flask-Admin to manage my posts. If I go to the admin area I can see a list of all my post from the DB but when I try to create a new one I got the next error:
Failed to create model. __init__() takes exactly 4 arguments (1 given)
This is my post model:
class Post(db.Model):
__tablename__ = 'news'
nid = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(100))
content = db.Column(db.Text)
created_at = db.Column(db.DateTime)
def __init__(self, title, content):
self.title = title.title()
self.content = content
self.created_at = datetime.datetime.now()
And this is my code to add the model to the UI:
from flask import Flask, session
from models import db, Post
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqlamodel import ModelView
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:pass@localhost/appname'
db.init_app(app)
admin = Admin(app)
admin.add_view(ModelView(Post, db.session))
I DO can edit models through the admin panel but not create new ones. I know I'm missing something really stupid but I can't figure out what it is.
Edit: it works if I don't implement init on the model. How can I fix this?
Take a look at the relevant part in the source code for Flask-Admin here.
The model is created without passing any arguments:
model = self.model()
So you should support a constructor that takes no arguments as well. For example, declare your __init__
constructor with default arguments:
def __init__(self, title = "", content = ""):
self.title = title.title()
self.content = content
self.created_at = datetime.datetime.now()
这篇关于无法在Flask-admin上创建模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!