Search code examples
pythonpython-2.7flaskpeeweeflask-peewee

AttributeError: 'list' object has no attribute '_meta'


Why does my code give me the error?

AttributeError: 'list' object has no attribute '_meta'

My Model.py Code

import datetime
from flask.ext.login import UserMixin
from peewee import *

DATABASE = SqliteDatabase('social.db')

class User(UserMixin, Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin = BooleanField(default=False)

    class Meta:
        database = DATABASE
        order_by = ('-joined_at',)

    @classmethod 
    def create_user(cls,user_name,email,password, admin=False):
        try:
            cls.create(
                user_name=user_name,
                email=email,
                password=generate_password_hash(password),
                is_admin=admin)
        except IntegrityError:
            raise valueError("User Already exists")

def initialize():
    DATABASE.connect()
    DATABASE.create_table([User],safe=True)
    DATABASE.close()

My main code in app.py

from flask import (Flask, g,render_template, flash, redirect, url_for)
from flask.ext.login import LoginManager

import forms
import models



DEBUG =True
PORT=8000
HOST = '127.0.0.1'

app = Flask(__name__)
app.secret_key = 'abcd.1234.xyz'

login_manager =LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(userid):
    try:
        return models.User.get(models.User.id==userid)
    except models.DoesNotExist:
        return None

@app.before_request
def before_request():
    """Connect to the database before each request."""
    g,db = models.DATABASE
    g.db.connect()


@app.after_request
def after_request(response):
    """Connect to the database after each request."""
    g.db.close()
    return response

@app.route('/register', methods=('GET', 'POST'))
def register():
        form = forms.RegisterForm()
        if form.validate_on_submit():
            flask("Yay, you registered", "success")
            models.User.create_user(
                username=form.username.data,
                email=form.email.data,
                password=form.password.data
            )
            return redirect(url_for('index'))
        return render_template('register.html', form=form)


@app.route('/index')
def index():
    return 'Hey'

if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            username='shuvanon',
            email='razik666@gmail.com',
            password='123456',
            admin=True
        )
    except ValueError:
        pass

    app.run(debug=DEBUG, host=HOST,port=PORT)

And my Error

Traceback (most recent call last):
File "app.py", line 59, in <module>
    models.initialize()
  File "F:\Python Work\Groupe\models.py", line 31, in initialize
    DATABASE.create_table([User],safe=True)
  File "D:\Program Files\Python27\lib\site-packages\peewee.py", line 3540, in create_table
    return self.execute_sql(*qc.create_table(model_class, safe))
  File "D:\Program Files\Python27\lib\site-packages\peewee.py", line 1929, in inner
    return self.parse_node(fn(*args, **kwargs))
  File "D:\Program Files\Python27\lib\site-packages\peewee.py", line 1948, in _create_table
    meta = model_class._meta
AttributeError: 'list' object has no attribute '_meta'

The model.py file is compiled properly, The social.db file is also created. I am new in flask and peewee and can't find the problem.


Solution

  • You passed in a list, not a single model here:

    DATABASE.create_table([User], safe=True)
    

    The Database.create_table() method only takes one model; the following would work:

    DATABASE.create_table(User, safe=True)
    

    You could also use the Database.create_tables() method (note the extra s at the end), which does require a sequence of models:

    DATABASE.create_tables([User], safe=True)
    

    Note that the Database.create_table() method (no trailing s) only creates the one table itself, and not any dependencies such as indexes or constraints. I suspect you simply made a typo and forgot the s.