Login

Load static media from secure (SSL) static server (Context Processor)

Author:
ianreardon
Posted:
October 9, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

If you request static files such as images, javascript or css using http rather than https, the browser will complain that your site is not secure.

This simple context processor will replace http:// with https:// in your MEDIA_URL if your static files are being included from an https page.

In your settings.py just replace 'django.core.context_processors.media' with your new context processor.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from django.conf import settings

def ssl_media(request):

  if request.is_secure():
    ssl_media_url = settings.MEDIA_URL.replace('http://','https://')
  else:
    ssl_media_url = settings.MEDIA_URL

  return {'MEDIA_URL': ssl_media_url}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

ianreardon (on October 9, 2009):

Should of put that this is a Context Processor in the title.

#

rpoulton (on October 10, 2009):

Why not just refer to your media using img src='//media.mydomain.com/image.jpg'?

Removing the http: from the URL will force the browser to request using either HTTP or HTTPS, based on the current request. It's just taking the relative path a step further - down to the protocol, not just the hostname.

#

Please login first before commenting.