2

I want to create a 404 Not Found error response with my custom message if the get request in accepts a jobCategoryId that has an alphabetic value.

The request format:

GET /JobProfilesByCategory/:jobCategoryId

views.py:

class JobProfilesByCategoryView(generics.ListAPIView):    
"""
    A custom view to create a view for Job profile by Category. Lookup_url_kwarg fetches the jobCategoryId variable from the URL 
"""
model=JobProfiles
serializer_class = JobProfilesByCategorySerializer
lookup_url_kwarg = "jobCategoryId"

def get_queryset(self):
    jobCategoryId = self.kwargs.get(self.lookup_url_kwarg)
    print(jobCategoryId)
    if(any(c.isalpha() for c in jobCategoryId)):
        return Response({"detail":"Not Found"},status=status.HTTP_404_NOT_FOUND)
    else:
        queryset = JobProfiles.objects.filter(jobCategoryId=jobCategoryId)
        return queryset

urls.py:

    url(r'JobProfilesByCategory/(?P<jobCategoryId>[-\w]+$)',view=views.JobProfilesByCategoryView.as_view()),#6th API
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
Vishesh Mehta
  • 79
  • 1
  • 9
  • Possible duplicate of [Django, creating a custom 500/404 error page](https://stackoverflow.com/questions/17662928/django-creating-a-custom-500-404-error-page) – Alessandro Da Rugna May 21 '19 at 06:40

1 Answers1

1

You could use NotFound

from rest_framework.exceptions import NotFound
...
def get_queryset(self):
    jobCategoryId = self.kwargs.get(self.lookup_url_kwarg)
    print(jobCategoryId)
    if (any(c.isalpha() for c in jobCategoryId)):
        raise NotFound({"custom_key": "Custom Error Message"})
    else:
        queryset = JobProfiles.objects.filter(jobCategoryId=jobCategoryId)
        return queryset
JPG
  • 82,442
  • 19
  • 127
  • 206