Will & Skill Developers

Will & Skill Developers

Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Erik S


HTML5 mode with angular.js & Django

Erik SErik S

Hi! I’m Erik, the last one of us developers here at Will & Skill to start blogging about the tech that we love and use. Today I will share a tip on how you can get pretty urls with angular.js html5 mode, while having django as your back end. I will share some code from one of my hobby projects so you guys can try it out for yourself. Happy coding!

Front end

In our angular app we need to set our $locationProviders html5 mode to true. A personal preference is to have a config.js file which holds various settings for the angular app. To set html5 mode to true you do this:


Notice how I also passed in another parameter “requireBase” which I set to false. Angular in html5 will by default require a base url tag to resolve relative paths. You can easily use one by simply including it in your head and pointing it to the entry point of your app like so:

  <base href="/">

OR you can set the requireBase parameter to false, this is supposedly bad for IE9 users. But I feel like IE9 users are bad for me, and thats how I roll!

Back end

So you’ve set up your front end with really slick urls, no hashbangs anymore! Now It’s time to make it work with an actual server. How to do that?

It’s really quite simple, we just need to redirect all urls to the entry point of our app, e.g base.html. In my apps main urls.py file I’ve set up some endpoints for an api, my admin url as well as endpoints to authenticate a user. All other urls are redirected to my app ‘core’s urls.py which serves the base.html file. The setup looks like this.

## THIS IS THE MAIN urls.py
urlpatterns = patterns('',  
    (r'^api/v1/me/', include('core.api.urls')),
    (r'^api/v1/locations/', include('locations.api.urls')),

    url(r'^api/docs/', include('rest_framework_swagger.urls')),

    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),

    url(r'^api-token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'),
    url(r'^api-token-refresh/', 'rest_framework_jwt.views.refresh_jwt_token'),

    url(r'^admin/', include(admin.site.urls)),

    url(r'^', include('core.urls')),
## THIS IS COREs urls.py
urlpatterns = patterns('',  
    url(r'^.*$', views.index, name='index'),

My index view then just serves the base.html and lets angular do the rest of the work. But do keep in mind:

With great power comes great responsibility

You now have to handle all incoming 404 errors with angular. But thats another post. Hope you guys enjoyed this!

Erik S

Erik S