I am trying my first django rest framework app, I am using djangorestframework==3.10.3
I created a simple project:
./mysite
./mysite/__init__.py
./mysite/settings.py
./mysite/urls.py
./mysite/wsgi.py
./db.sqlite3
./polls
./polls/migrations
./polls/migrations/__init__.py
./polls/models.py
./polls/__init__.py
./polls/apps.py
./polls/admin.py
./polls/exceptions.py
./polls/tests.py
./polls/urls.py
./polls/views.py
./manage.py
I have one view in the polls application which only throws a ParseError which is an ApiException (according to the documentation it is handled by custom exception https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling)
from django.views.decorators.csrf import csrf_exempt
from rest_framework.exceptions import ParseError
# Create your views here.
@csrf_exempt
def test_view(request):
raise ParseError("test!", 409)
Here is my custom exception, which is at polls/exceptions.py
from rest_framework.views import exception_handler
def base_exception_handler(exc, context):
print('DEBUUUUUUUUUG!!!!!!!')
return JsonResponse({"message": "base exception", "status": 404}, status=404)
And finally the mysite/settings.py - registering the custom exception handler (all the rest of the file is default):
...
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
...
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'polls.exceptions.base_exception_handler',
}
when running the server and navigating to the view which is defined at http://localhost:8000/test I get:
Then I tried to check whether default exception handler is executed by setting a breakpoint at rest_framework.views.exception_handler (I didn't change any setting for it so it should use default as described in the documentation), however it is not called. I get an HTML page in response.
Here are the packages I am using (requirements.txt):
Django==2.2.7
djangorestframework==3.10.3
pytz==2019.3
sqlparse==0.3.0
Thank you for your help
If anyone is facing the same problem, here is the solution. The problem is that function view is missing the @api_view() decorator, this fixes the problem:
from django.views.decorators.csrf import csrf_exempt
from rest_framework.exceptions import ParseError
from rest_framework.decorators import api_view
# Create your views here.
@csrf_exempt
@api_view()
def test_view(request):
raise ParseError("test!", 409)
It would have been great if the documentation be more detailed about it.