This snippet will add the subdomain and domain to the request object for use in your views.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class SubdomainMiddleware: """ Make the subdomain publicly available to classes """ def process_request(self, request): domain_parts = request.get_host().split('.') if (len(domain_parts) > 2): subdomain = domain_parts[0] if (subdomain.lower() == 'www'): subdomain = None domain = '.'.join(domain_parts[1:]) else: subdomain = None domain = request.get_host() request.subdomain = subdomain request.domain = domain |
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
This is useful, thanks.
However, it might be safer to use the request get_host() method instead of META['HTTP_HOST'], because it is not guaranteed to be set. E.g. in tests, META['HTTP_HOST'] is not defined.
#
Thanks. I've updated the snippet.
#
usefull. more intuitive than django-subdomains app.
#
Please login first before commenting.