Newtt
Newtt

Reputation: 6190

Use html5Mode true in AngularJS with Django

I'm using an AngularJS app with Django Rest Framework. However, I've setup my project such that the Angular page is served from within the templates folder of my setup such that

url(r'^$', index)

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

I'm running the angular app on / url of Django and have setup my ngRoutes as 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 such as localhost:8000/some-random-url, it'll redirect to Django's inbuilt 404 page. Is there a way for me to fix this? Or do I have to completely abstract the angular app from the rest framework?

Upvotes: 4

Views: 1191

Answers (2)

Ian Juma
Ian Juma

Reputation: 107

With Django/ DRF, for a series of routes have the index route with the .*$ as the last:

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'

where index is the last route.

Upvotes: 1

levi
levi

Reputation: 22697

You need to add in your angularjs router, the default route value (otherwhise)

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

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

Then add this to the bottom of your urls.py

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

This means that if requested url did not match any previous url rules, redirect to index. Notice * in ^.*$

Upvotes: 4

Related Questions