user6946961 user6946961 - 1 month ago 17
React JSX Question

How do i configure django urls to make it so if it displays 404, it reroutes to Reactjs

The title is terrible - sorry about that.

So say I have a website say www.myhairynose.com/. I've configured my urls.py so that whenever the person enters www.myhairynose.com it redirects them to the index.html (where it displays the reactjs application). I've set reactjs with react-router and made it so when you click a button on the index page it goes to www.myhairynose.com/#/webpage.

Thing is... I don't want that.

I want it to go to www.myhairnose.com/webpage. I want react to handle this however and not django. ALL of this url thing should be in the same application of index.html. How do I configure django urls.py so that if I enter www.myhairynose.com/webpage it goes to the index of www.myhairnose.com ReactJs's application and then it checks to see if the route has webpage. Otherwise say if I went to www.myhairynose.com/asdkjaskldsaj (which the react route doesn't have) it should display a 404.

______TLDR______
Basically what I want to happen:

User goes to website.com/name
>if website.com/name exists in django - it returns a html doc
>if not then it redirects to website.com/ where ReactJs will handle the url and see if it matches any of the routers
...> if it does, then it displays that route
...> if not then it displays a django 404 or a custom 404 page.


How do I configure django and reactjs to do this?

Answer

Are you using Django to render react? I am making the assumption that you have some view like views.LoadReactView.

What you need is a catch all route.

from django.contrib import admin
from myapp import views

urlpatterns = [
    ...
    url(r'^admin', admin.site.urls),
    url(r'^', views.LoadReactView.as_view()),
] 

This should appear as your very last pattern. You essentially are saying "after checking all the other routes, if there are no matches, go here".

In addition, you could also actually just define your main view as your 404 handler

urlpatterns = [
    ...
]

handler404 = views.LoadReactView.as_view