Skip to content

Commit 9d2a2bf

Browse files
author
Yehor Komarov
committed
Demonstrate form validation in examples
1 parent 15a9243 commit 9d2a2bf

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

examples/sqla/views.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
row_action,
1313
)
1414
from starlette_admin.contrib.sqla import ModelView
15-
from starlette_admin.exceptions import ActionFailed, FormValidationError
15+
from starlette_admin.exceptions import FormValidationError
1616

17-
from .models import Post, Tag, User
17+
from .models import Post, User
1818

1919
AVAILABLE_USER_TYPES = [
2020
("admin", "Admin"),
@@ -68,19 +68,24 @@ async def validate(self, request: Request, data: Dict[str, Any]) -> None:
6868
raise FormValidationError(errors)
6969
return await super().validate(request, data)
7070

71+
async def validate_add_tag(self, request: Request, data: Dict[str, Any]):
72+
errors: Dict[str, str] = {}
73+
if data["tag"] is None:
74+
errors["tag"] = "You must specify a tag"
75+
if len(errors) > 0:
76+
raise FormValidationError(errors)
77+
7178
@action(
7279
name="add_tag",
7380
text="Add a tag for selected posts",
7481
icon_class="fas fa-tag",
7582
confirmation="Are you sure you want to add a tag to all of these posts?",
7683
form_fields=[HasOne("tag", identity="tag")],
7784
)
78-
async def add_tag(self, request: Request, pks: List[Any]):
79-
form = await request.form()
80-
tag_pk = form["tag"]
81-
tag = await TagView(Tag).find_by_pk(request, tag_pk)
82-
if not tag:
83-
raise ActionFailed("Tag is missing")
85+
async def add_tag(self, request: Request, pks: List[Any], data: Dict):
86+
await self.validate_add_tag(request, data)
87+
88+
tag = data["tag"]
8489
posts = await self.find_by_pks(request, pks)
8590
for post in posts:
8691
post.tags.append(tag)
@@ -97,9 +102,8 @@ async def add_tag(self, request: Request, pks: List[Any]):
97102
EnumField("status", choices=AVAILABLE_POST_STATUSES, select2=False)
98103
],
99104
)
100-
async def approve(self, request: Request, pk: Any):
101-
form = await request.form()
102-
status = form["status"]
105+
async def approve(self, request: Request, pk: Any, data: Dict):
106+
status = data["status"]
103107
post = await self.find_by_pk(request, pk)
104108
post.status = status
105109
request.state.session.commit()

0 commit comments

Comments
 (0)