Load static media from secure (SSL) static server (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. Use MEDIA_URL in flatpages with SSL by gobble 2 years, 10 months ago
  2. Context processor for django admin app_list by alexander 3 years, 3 months ago
  3. Cycling MEDIA_URL context processor by girasquid 4 years, 5 months ago
  4. Use MEDIA_URL in flatpages by robhudson 5 years, 2 months ago
  5. Use MEDIA_URL in 500 error page by bthomas 4 years, 6 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.

#

thedod (on November 30, 2009):

I have a different ssl url (say https://example.hosting-provider.com for http://example.com), so I've added HTTP_HOME and HTTPS_HOME to settings.py and I use

settings.MEDIA_URL.replace(settings.HTTP_HOME,settings.HTTPS_HOME)

Thanks for showing me how to solve this problem

#

imns (on October 13, 2010):

If you are hosting on webfactions, then request.is_secure() doesn't work correctly, so you need to also check:

if 'HTTP_X_FORWARDED_SSL' in request.META:

You can check out the _is_secure method for an example of how to use this in this snippet: http://djangosnippets.org/snippets/85/

#

(Forgotten your password?)