1111import aiohttp_admin
1212from aiohttp_admin .backends .sqlalchemy import SAResource
1313
14+ JS = """
15+ const odd = () => (value, allValues) => {
16+ if (value % 2 === 0)
17+ return "Votes must be an odd number";
18+ return undefined;
19+ };
20+
21+ export const validators = {odd};
22+ """
23+
1424
1525class Base (DeclarativeBase ):
1626 """Base model."""
@@ -26,13 +36,18 @@ class User(Base):
2636 votes : Mapped [int ] = mapped_column ()
2737
2838 __table_args__ = (sa .CheckConstraint (sa .func .char_length (username ) >= 3 ),
29- sa .CheckConstraint (votes >= 1 ), sa .CheckConstraint (votes < 5 ))
39+ sa .CheckConstraint (votes >= 1 ), sa .CheckConstraint (votes < 6 ),
40+ sa .CheckConstraint (votes % 2 == 1 ))
3041
3142
3243async def check_credentials (username : str , password : str ) -> bool :
3344 return username == "admin" and password == "admin"
3445
3546
47+ async def serve_js (request : web .Request ) -> web .Response :
48+ return web .Response (text = JS , content_type = "text/javascript" )
49+
50+
3651async def create_app () -> web .Application :
3752 engine = create_async_engine ("sqlite+aiosqlite:///:memory:" )
3853 session = async_sessionmaker (engine , expire_on_commit = False )
@@ -41,10 +56,11 @@ async def create_app() -> web.Application:
4156 async with engine .begin () as conn :
4257 await conn .run_sync (Base .metadata .create_all )
4358 async with session .begin () as sess :
44- sess .add (User (username = "Foo" , votes = 4 ))
59+ sess .add (User (username = "Foo" , votes = 5 ))
4560 sess .add (User (username = "Spam" , votes = 1 , note = "Second user" ))
4661
4762 app = web .Application ()
63+ app .router .add_get ("/js" , serve_js , name = "js" )
4864
4965 # This is the setup required for aiohttp-admin.
5066 schema : aiohttp_admin .Schema = {
@@ -54,7 +70,12 @@ async def create_app() -> web.Application:
5470 },
5571 "resources" : ({"model" : SAResource (engine , User ),
5672 "validators" : {User .username .name : (("regex" , r"^[A-Z][a-z]+$" ),),
57- User .email .name : (("email" ,),)}},)
73+ User .email .name : (("email" ,),),
74+ # Custom validator from our JS module.
75+ # Min/Max validators are automatically included.
76+ User .votes .name : (("odd" ,),)}},),
77+ # Use our JS module to include our custom validator.
78+ "js_module" : str (app .router ["js" ].url_for ())
5879 }
5980 aiohttp_admin .setup (app , schema )
6081
0 commit comments