coleifer / flask-peewee

flask integration for peewee, including admin, authentication, rest api and more
http://flask-peewee.readthedocs.org/
MIT License
776 stars 181 forks source link

Dynamically adding/registiring models to the admin panel #99

Open beng opened 10 years ago

beng commented 10 years ago

I'm able to generate models on the fly based on the parameters in my request, but I'm running into issues registering the newly created model with the admin panel; mainly because the admin is instantiated at the start of the web-server, and the models are generated on a request-by-request basis.

Below is the code I'm using to generate the models on the fly:

def create_model(name, fields=None, module='', admin_opts=None):
    class GenericModel(db.Model):
        pass

    class Admin(ModelAdmin):
        pass

    attrs = {'__module__': module, 'GenericModel': GenericModel}

    legal_types = {
        'CharField': CharField
    }

    # just for testing; peewee requires a primary key
    IntegerField(primary_key=True).add_to_class(db.Model, 'id')

    if fields:
        for idx, pg_info in fields.items():
            field_type = legal_types[pg_info['field_type']]
            field_name = pg_info['field_name']
            field_type().add_to_class(db.Model, field_name)

    model = type(name, (db.Model,), attrs)
    model.create_table(fail_silently=True)

    for k, v in admin_opts.items():
        setattr(Admin, k, v)

    admin.register(model, Admin)

    return model

The error I'm getting is

werkzeug.routing.BuildError 
BuildError: ('admin.<class name here>_index', {}, None)

I made sure that admin._registry contains my newly created model.__class__ and Admin.__class__ as a (key, value) pair. Any ideas on how to go about this or what I need to modify to get this to work? Ideally, I want to see the models that are created on-the-fly reflected in my admin panel.

Thanks.

coleifer commented 10 years ago

Will look into a fix.