Handling single page application url and django url

Robin picture Robin · Mar 17, 2017 · Viewed 8.6k times · Source

I have a single page application created in Vue.js that utilizes the HTML5 History Mode for routing, and the html file is served with Django.

The urls.py of django is like so:

urlpatterns = [
    url(r'^$', views.home),
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
]

And views.home:

def home(request):
    return render(request, 'index.html')

Consider the following scenario:

  1. User visits the home page (i.e., /)

Since, the home page responds with required index.html for the Single page Vuejs app, it works like its supposed to.

  1. From there the user navigates to the about page (i.e., /username/12).

Its still working fine, as its navigating with the Vue router.

  1. Now, the user refreshes the page.

Since there's no /username/12 in the urls.py patterns, it will show Page not found (404).

Now, I could provide another pattern in urls.py to catch all pattern in the last order as this:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^.*$', views.home),
]

But other urls like the media or static urls will also point to the same catch all pattern regex. How can I solve this problem?

Answer

Bllli picture Bllli · Oct 7, 2017

I have a similar problem.

How can I use vue-router and django rest framework the same time?

This is my solution to this problem. Hope it helps you.

Expected results:

http://127.0.0.1:8000/       <-- TeamplateView index.html using vue
http://127.0.0.1:8000/course <-- vue-router
http://127.0.0.1:8000/api    <-- rest framework
http://127.0.0.1:8000/admin  <-- django admin

and I try this and it works!

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/', include(router.urls)),
    url(r'^.*$', TemplateView.as_view(template_name="index.html")),
]

The order is important, url(r'^.*$', TemplateView.as_view(template_name="index.html")), is the last one

and this is my vue router

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [{
      path: '/courses',
      component: CourseSet
    }, {
      path: '/',
      component: hello
    }]
})

My project on GitHub