HTML5 mode with angular.js & Django

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:

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

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!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.