Use html5Mode true in AngularJS with Django

I am using the application AngularJSwith Django Rest Framework. However, I set up my project so that the Angular page is inside the folder of templatesmy settings, so

url(r'^$', index)

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

I am running an Angular application on a /Django url and configured my ngRoutesas follows:

var sgApp = angular.module('sgApp', [
        'ngRoute',
    ]);

sgApp.config(['$routeProvider','$locationProvider',
    function($routeProvider, $locationProvider){
        $routeProvider.when('/',{
            templateUrl: '/static/partials/index.html'
        });
        $locationProvider.html5Mode(true);
    }
]);

However, when I try to access an invalid URL, for example localhost:8000/some-random-url, it redirects to the inline Django page 404. Is there any way for me to fix this? Or do I need to completely abstract the Angular application from the rest of the structure?

+4
source share
2 answers

angularjs, (otherwhise)

sgApp.config(['$routeProvider','$locationProvider',
    function($routeProvider, $locationProvider){
        $routeProvider.when('/',{
            templateUrl: '/static/partials/index.html'
        })
        .otherwise({
            redirectTo: '/'
         });

        $locationProvider.html5Mode(true);
    }
]);

urls.py

url(r'^.*$', index),

, URL- URL-, index. * ^.*$

+4

Django/DRF .*$ :

urlpatterns = patterns(
    '',
    url(r'^api/v1/', include(router.urls)),
    url(r'^api/v1/', include('agents.urls')),
    url(r'^api/v1/', include('utils.urls')),
    url(r'^api/v1/', include('authentication.urls')),
    url(r'^api/v1/', include('products.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^accounts/login', LoginView.as_view(), name='login'),
    url(r'^.*$', IndexView.as_view(), name='index'),
)
handler404 = 'views.handle_page_not_found_404'

index - .

+1

All Articles