skip to Main Content

I’m having a problem getting handler 404 to redirect to my homepage. Here’s what I have and tried…

In settings.py

DEBUG=False

In views.py

class view_404(request, exception=None):
  return render(request, "mysite/index.html")

In urls.py

From django.conf.urls import handler404

urlpatterns = [
  path('', views.index, name='index')
]

handler404 = "mysite.views.index"

I’ve tried putting the view_404 function directly in the urls.py file, I’ve tried handler404 = views.index. I’ve tried handling 404s in my nginx.conf file

error_page 404 =200 /index.html;

and

error_page 404 /index.html;
location /index.html {
  root path/to/template;
  internal;
}

I have not been able to get any of these to work…

2

Answers


  1. Chosen as BEST ANSWER

    So the problem was that it it needs to be handled in the projects root urls.py file and it acts globally for all apps


  2. Create a view which redirect to your index:

    def my_404_view(request):
        return redirect("index")
    

    And reference to this view in your urls.py file:

    handler404 = "mysite.views.my_404_view"  # or whatever path you need
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search