angular django rewrite unmatched urls to index.html (angular app)

546 Views Asked by At

I have a django server and an angular app.

I am able to launch the angular app and navigate to the various parts of the site using links i have added to the app.

But if I want to go to a part of the site directly I get a 404 error.

example if I have a link in my app that directs me to

niftysite.com/team 

it works

but if I put in my browsers url

niftysite.com/team 

it fails with 404

I understand this is because the default behavior is to look for the link to the page in the servers urls.

I also understand that the fix is to have server side 404s redirect to the angular index.html page with the route params included.

My question is how?

I have already started on an implementation but I am not sure how to fix it. Any guidance the rest of the way through would be helpful.

here is what I have so far.

urls.py

handler404 = views.error_404

views.py

from django.shortcuts import render

def error_404(request):
    data = {}
    return render(request, 'index.html', data)

similar to this question, but I am not using Nginx

How to redirect 404 requests to homepage in Django single page app using Nginx?

1

There are 1 best solutions below

0
AudioBubble On

Here is the implementation:

urls.py

url(r'^.*$', views.PassToAngular.as_view()) 

make sure this url is the last url in your urls array.

views.py

from django.shortcuts import render
from django.views.generic import TemplateView


    class PassToAngular(TemplateView):

        def get(self, request, **kwargs):
            return render(request, 'index.html', context= None)

thanks to MihirKavatkar for your help!