Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask
- import peewee
- from flask.ext import admin
- from flask.ext.admin.contrib.peewee import ModelView
- app = Flask(__name__)
- app.config['SECRET_KEY'] = '123456790'
- db = peewee.SqliteDatabase('test.sqlite', check_same_thread=False)
- class BaseModel(peewee.Model):
- class Meta:
- database = db
- class User(BaseModel):
- username = peewee.CharField(max_length=80, unique=True, null = False)
- email = peewee.CharField(max_length=120)
- def __unicode__(self):
- return self.username
- class UserInfo(BaseModel):
- key = peewee.CharField(max_length=64)
- value = peewee.CharField(max_length=64)
- user = peewee.ForeignKeyField(User)
- def __unicode__(self):
- return '%s - %s' % (self.key, self.value)
- class Post(BaseModel):
- title = peewee.CharField(max_length=120)
- text = peewee.TextField(null=False)
- date = peewee.DateTimeField()
- user = peewee.ForeignKeyField(User)
- def __unicode__(self):
- return self.title
- from wtforms.validators import ValidationError
- class UserAdmin(ModelView):
- def no_root_allowed(form, field):
- if field.data == 'root':
- raise ValidationError('"root" is not allowed')
- inline_models = (UserInfo,)
- form_args = dict(
- username=dict(validators=[no_root_allowed])
- )
- def on_model_change(self, form, model, is_created):
- return super(UserAdmin, self).on_model_change(form, model, is_created)
- def update_model(self, form, model):
- return super(UserAdmin, self).update_model(form, model)
- def create_model(self, form):
- return super(UserAdmin, self).create_model(form)
- def delete_model(self, model):
- return super(UserAdmin, self).delete_model(model)
- pass
- class PostAdmin(ModelView):
- column_exclude_list = ['text']
- column_sortable_list = ('title', ('user', User.email), 'date')
- column_searchable_list = ('title', User.username)
- column_filters = ('title', 'date', User.email)
- form_ajax_refs = { 'user': { 'fields': (User.username, 'email') } }
- @app.route('/')
- def index():
- return '<a href="/admin/">Click me to get to Admin!</a>'
- if __name__ == '__main__':
- import logging
- logging.basicConfig()
- logging.getLogger().setLevel(logging.DEBUG)
- admin = admin.Admin(app, 'Peewee Models')
- admin.add_view(UserAdmin(User))
- admin.add_view(PostAdmin(Post))
- try:
- User.create_table()
- UserInfo.create_table()
- Post.create_table()
- except:
- pass
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement