Search code examples
djangodjango-rest-frameworkdjango-react

Handling Django Rest Framework 404 page directed to react app's home/index


I have DRF project and the react project is also within the Django project as an application. The name of the react application is frontend.

INSTALLED_APPS = [
....
'frontend'
]

The structure of the frontend is as follows,

enter image description here

The only code in the project is in views,

def index(request):
    return render(request, "build/index.html")

And the URL is,

from frontend.views import index
urlpatterns += [path("", index, name="index")]

Now what I was trying to do is, if the browser's URL response is 404, then instead of showing django's 404 page I would like to go the home/index of the frontend react app. I tried to add handler404 = 'frontend.views.index' in urls.py, but it shows 500 internal error instead of 404 or the index of react app.

Any help would be really appreciated. Thanks in Advance.


Solution

  • This worked for me in regular django project.

    def handler404(request, exception):
        return render(request, '404.html', status=404)
    
    

    Here, 404.html is my custom template file.

    and in my main urls.py:

    handler404 = myapp.views.handler404
    handler500 = myapp.views.handler500