title: One view for multiple sub-domains using django-hosts
body: <p>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 <a href="http://django-hosts.readthedocs.io/en/latest/index.html" rel="noreferrer">django-hosts</a> library to set up sub domains. </p>
  
  <p>hosts file:</p>
  
  <pre><code>127.0.0.1       localhost
  127.0.0.1       myproject.io
  127.0.0.1       www.myproject.io
  127.0.0.1       company1.myproject.io
  127.0.0.1       company2.myproject.io
  </code></pre>
  
  <p>settings.py:</p>
  
  <pre><code>ROOT_URLCONF = 'core.urls'
  ROOT_HOSTCONF = 'core.hosts'
  DEFAULT_HOST = 'www'
  DEFAULT_REDIRECT_URL = "http://www.myproject.io:8000"
  </code></pre>
  
  <p>core/hosts.py:</p>
  
  <pre><code>from hostsconf import urls as redirect_urls
  host_patterns = [
      host(r'www', settings.ROOT_URLCONF, name='www'),
      host(r'(?!www).*', redirect_urls, name='wildcard'),
  ]
  </code></pre>
  
  <p>hostsconf/urls.py:</p>
  
  <pre><code>from .views import wildcard_redirect
  
  urlpatterns = [
      url(r'^(?P&lt;path&gt;.*)', wildcard_redirect)
  ]
  </code></pre>
  
  <p>hostsconf/views.py:</p>
  
  <pre><code>DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.myproject.io:8000")
  
  def wildcard_redirect(request, path=None):
      new_url = DEFAULT_REDIRECT_URL
      if path is not None:
          new_url = DEFAULT_REDIRECT_URL + "/" + path
      return HttpResponseRedirect(new_url)
  </code></pre>
  
  <p>I have a few problems now:</p>
  
  <ol>
  <li>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 <code>Invalid HTTP_HOST header: 'company1.myproject.io:8000'. You may need to add u'company1.myproject.io' to ALLOWED_HOSTS</code>
  Do I really need each time add new host to ALLOWED_HOSTS when I got new sub domain or I am doing something wrong?</li>
  <li><p>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:</p>
  
  <pre><code>def home_page(request):
      subdomain = 'somehow get sub domain (company1 or company2)'
      comp = User.objects.get(domain_name=subdomain)
      return redirect(request, 'tpl.html', {"company": comp})
  </code></pre></li>
  </ol>
  
  <p>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?</p>