Skip to content
Advertisement

One view for multiple sub-domains using django-hosts

I need to have multiple sub domains for my project. Each sub domain represents some company. For example: company1.myproject.io, company2.myproject.io. I used django-hosts library to set up sub domains.

hosts file:

JavaScript

settings.py:

JavaScript

core/hosts.py:

JavaScript

hostsconf/urls.py:

JavaScript

hostsconf/views.py:

JavaScript

I have a few problems now:

  1. When I go to myproject.io it succesfully redirects me to the www.myproject.io. But when I go to company1.myproject.io I got an Invalid HTTP_HOST header: 'company1.myproject.io:8000'. You may need to add u'company1.myproject.io' to ALLOWED_HOSTS Do I really need each time add new host to ALLOWED_HOSTS when I got new sub domain or I am doing something wrong?
  2. How to implement a single view for all sub-domains where will be dynamic context for each company. Basically I need to make queries into the db by sub domain name. Example:

    JavaScript

UPDATE: Figured out how to handle ALLOWED_HOSTS and get a subdomain. But I still don’t get how to implement single view for my sub domains. Do I need to create another pattern in hosts.py?

Advertisement

Answer

A value beginning with a period can be used as a subdomain wildcard: ‘.example.com’ will match example.com, www.example.com, and any other subdomain of example.com. https://docs.djangoproject.com/en/1.11/ref/settings/#allowed-hosts

For security purposes you must add your domains to allowed_hosts list. Just use wildcard like this:

JavaScript

2) Try HttpRequest.META[“HTTP_HOST”]

https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.META

or request.get_host()

UPDATE: If you want operate with multiple sites in single django application, you should use Django Sites framework. You don’t need django-hosts library.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement