0

I'm trying to create a SPA with Vue in my Django project, so that Django handles only authentication templates and the rest of the frontend is entirely Vue rendered by webpack-loader, so it's Django rendering the Vue app. I'm doing this in order not to lose the benefits of having authentication handled entirely by Django.

So everything below /accounts/ will be handled by Django templates rendered by django views, while everything below /app/ will be handled by the Vue application.

I have the following:

urlpatterns = [
    # Some standard django templates url here for authentication..
    # ...
    # The Vue app:
    path('app/', views.vueApp, name='vueApp'),
]

So when the user navigates to mysite.com/app, Vue will handle the whole frontend as a SPA with its routes:

//main.js
const router = new VueRouter({
  base: '/app',
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/test1', component: testcomponent },
    { path: '/test2', component: test2component }
  ]
})

The problem with my code, is that if i click on a link to test1 or to test2 from inside the Vue app, i will get redirected to testcomponent (mysite.com/app/test1) and test2component (mysite.com/app/test2); instead, if i open my browser and i navigate directly to mysite.com/app/test1 or mysite.com/app/test2 i will get a Page Not Found error by Django, i think because Django thinks i'm trying to reach a standard Django url, while instead i'm trying to reach an URL handled by my Vue app.

Is there any way to solve this? Thanks in advance!

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
JayK23
  • 287
  • 1
  • 15
  • 49
  • See this answer https://stackoverflow.com/questions/42864641/handling-single-page-application-url-and-django-url – NKSM Mar 22 '21 at 13:34

1 Answers1

2

To deal with this, you need a catch-all route to ensure that you capture everything after that / in your url as well. Otherwise it looks like your url is not a match. You need something like this (if you're using regex to match):

path('app/?.*$', views.vueApp, name='vueApp'),

This should match everything that starts with app/ and has other stuff after it as well. You don't care about capturing that stuff with django bc the vue router will handle it from that point.

ETA: If you're NOT using regex, I think you can use this format to accept whatever comes after the slash:

path('app/<path:rest_of_path>', views.vueApp, name='vueApp'),
Ashley H.
  • 689
  • 4
  • 11