Make sure to import this at the top
import re
from django.http import JsonResponse
from django.utils.translation import gettext_lazy as _
from django.conf.urls import handler404
You can have this inside your function/method to determine if from browser or ajax call
requested_html = re.search(r'^text/html', request.META.get('HTTP_ACCEPT'))
if requested_html:
# requested from browser, do as per your wish
# ajax call. Returning as per wish
return JsonResponse({
'detail': _('Requested API URL not found')
}, status=404, safe=False)
Explanation
If you request to load a page from a browser, you would see in the network tab under the requested headers of that request, text/html
is at the beginning of requested headers
.
However, if you are making an ajax call from the browser, the requested headers
has */*
in the beginning. If you attach
Accept: application/json
in the header, then requested headers become this
From this, you can understand how the accept header is different in these cases.