pythonflaskflask-sqlalchemyflask-admin

Unable to create models on Flask-admin


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?


Solution

  • 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()