Adding custom fields to kotti Principal class

Since the Principal schema is already defined in Kotti and mapped to the database, it requires a schema override by defining a new class with the __tablename__ pointing to the principals table.
Adding custom fields to kotti Principal class

Users and groups in Kotti are created and managed by a single class, the Principal class. The Principal class is an SQLAlchemy schema class, which defines the fields and functionality of each user and group in Kotti. This class creates a principals table in the database to store all the users and groups data. Since the Principal schema is already defined and mapped to the database, it requires a schema override by defining a new class with the __tablename__ pointing to the principals table.  The snippet below, we created a User schema based on the Principal schema from Kotti and added our own columns or fields to the database.

# secuirty.py

from kotti.security import Principal as KPrincipal
from sqlalchemy.ext.declarative import declared_attr,
from sqlalchemy import Unicode

from my.package import _


class User(KPrincipal):
    """ User and Group """
    tablename = 'principals'

    # Allow table inheritance from the parent class
    __table_args__ = {'extend_existing': True}

    @declared_attr
    def __tablename__(cls):
        return cls.tablename

    rank = Column(Unicode(20), default="")
    status = Column(Unicode(20), default="")

    
class Users(Principals):
    factory = User


def principals_factory():
    return Users()

In addition, we created a Users class, which uses the User class as the factory class that will be returned by the principals_factory function. By doing this, the get_principals function from the kotti.security package will return our newly define schema object for each user. Lastly, we need to register our new schema for the principals table by setting the kotti.principals_factory setting to our newly defined principals_factory function as seen in the snippet below.

def kotti_configure(settings):
    settings['kotti.principals_factory'] = \
        'my.package.security.principals_factory'
Note, if your database already exist, you will be required to do a database migration. See kotti documentation on database migration for more information.
Go Back
Menu
×