-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpetra_dto.py
40 lines (31 loc) · 1.2 KB
/
petra_dto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from functools import wraps
from rest_framework.exceptions import ValidationError
def petra_dto(form_class):
"""
Decorator that validates incoming request data using a form class.
Handles both JSON and form-encoded data.
Args:
form_class: Django Form class to validate the request data
"""
def decorator(view_func):
@wraps(view_func)
def wrapper(self, request, *args, **kwargs):
if request.content_type == 'application/json':
form = form_class(request.data)
else:
form = form_class(request.POST)
if form.is_valid():
return view_func(self, request, form, *args, **kwargs)
# Format the error response
formatted_errors = {
'success': False,
'errors': {}
}
for field, error_list in form.errors.items():
# Convert to array format
formatted_errors['errors'][field] = [
f"The {field} {error_list[0]}" # Format error message
]
raise ValidationError(formatted_errors)
return wrapper
return decorator