Using Django to serve parts of your site over HTTPS

Firstly, you'll need to get your web server up and running with https, you'll needyour certificate and key set up, happily theres already loads of posts about that,so I won't cover it here!

The second area of pain is that djangos development runserver doesn't support HTTPS,which is irksome but apparently there are ways around it! The django-weave projectgo into detail about it. I'm lucky in that I run vm's to mimic my production environment, but I often use runserver as well as its just plain handy.

To serve parts of the site as HTTPS I just decorate the views and check the `is_secure()` flag. Then I redirect to the secure version!

Simple stuff, but part of the problem is the url template tag does local urls, so once they are on HTTPS how do we ensure that they use HTTP for other parts of the site? To do this I use a middleware that checks for the flag set on the request in the decorator:

That ensures that I go back to HTTP versions of pages that should be served by HTTP.

A final pain is managing mixed content type warnings, which happens when a web page is served via HTTPS but the assets are served by HTTP, this is bad as it could undermine the security of the whole page - so dont do it! You'll need to handle it so you'll have to add checks like:

{% if request.is_secure %}https{% else %}http{% endif %}

Make it easy by writing a template tag to do it and don't forget and js widgets like addthis!