Skip to content

Instantly share code, notes, and snippets.

@xeor
Created October 29, 2014 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeor/2a0de36f7d686448408a to your computer and use it in GitHub Desktop.
Save xeor/2a0de36f7d686448408a to your computer and use it in GitHub Desktop.
Set this as middleware in your Django app if you need to get reverse urls to work, and dont access Django on port 80 or 443 (as is often the case on developer environments (specially using Docker))
import os
class ServerURLWithPortHackMiddlware(object):
"""
A way to set HTTP_HOST to HTTP_HOST + (a port number).
This is usefull when you want to run Django on your local computer as a
developer server. Example in Docker.
Django doesn't know which PORT you are using all the way to the browser,
so if you don't fix this, reverse URLs will be all wrong..
"""
def process_request(self, request):
if os.environ.get('HTTP_PORT', None) and request.META.get('HTTP_HOST', None):
request.META['HTTP_HOST'] = '{}:{}'.format(request.META['HTTP_HOST'], os.environ['HTTP_PORT'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment