Make invalid search input explicit in UI and API
This commit is contained in:
@ -1,5 +1,7 @@
|
||||
from rest_framework import generics
|
||||
from rest_framework import status
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
|
||||
|
||||
from apps.competitions.models import Competition, Season
|
||||
@ -39,17 +41,35 @@ class PlayerSearchApiView(ReadOnlyBaseAPIView, generics.ListAPIView):
|
||||
serializer_class = PlayerListSerializer
|
||||
pagination_class = ApiPagination
|
||||
|
||||
def get_search_form(self):
|
||||
if not hasattr(self, "_search_form"):
|
||||
self._search_form = PlayerSearchForm(self.request.query_params)
|
||||
return self._search_form
|
||||
|
||||
def _validation_error_response(self):
|
||||
form = self.get_search_form()
|
||||
return Response(
|
||||
{
|
||||
"detail": "Invalid search parameters.",
|
||||
"errors": form.errors.get_json_data(escape_html=True),
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
form = self.get_search_form()
|
||||
if form.is_bound and not form.is_valid():
|
||||
return self._validation_error_response()
|
||||
return super().list(request, *args, **kwargs)
|
||||
|
||||
def get_queryset(self):
|
||||
form = PlayerSearchForm(self.request.query_params or None)
|
||||
form = self.get_search_form()
|
||||
queryset = base_player_queryset()
|
||||
if form.is_valid():
|
||||
queryset = filter_players(queryset, form.cleaned_data)
|
||||
sort_key = form.cleaned_data.get("sort", "name_asc")
|
||||
if sort_key in METRIC_SORT_KEYS:
|
||||
queryset = annotate_player_metrics(queryset, form.cleaned_data)
|
||||
queryset = apply_sorting(queryset, sort_key)
|
||||
else:
|
||||
queryset = queryset.order_by("full_name", "id")
|
||||
queryset = filter_players(queryset, form.cleaned_data)
|
||||
sort_key = form.cleaned_data.get("sort", "name_asc")
|
||||
if sort_key in METRIC_SORT_KEYS:
|
||||
queryset = annotate_player_metrics(queryset, form.cleaned_data)
|
||||
queryset = apply_sorting(queryset, sort_key)
|
||||
return queryset
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user