Search code examples
pythondjangodjango-viewssubdomainview

How to capture the subdomain in a django view?


I'm developing an aplication in django with many subdomains. For example www.mysite.com, mx.mysite.com, es.mysite.com, nz.mysite.com All of these patterns have to redirect to the same django aplication and render the html page with the country language.

is there any way to capture the sub domain in the views.py?

I want something like this in views.py:

######## VIEWS.PY ###########
def hompage(request):
    subdomain = #HERE IS WHERE I WANT TO CAPTURE THE SUBDOMAIN 
    if subdomain=='www':
        contextdict = {"Language": "English"}
    else if subdomain=='mx':
        contextdict = {"Language": "Spanish"}
    return render(request, 'mysite/index.html', contextdict)

Solution

  • Basically, the question consists of three parts:

    1. How to get the url in the view. Answered here
    2. How to parse url. Can be found here if you have Python 3
    3. Finally, you need to get the subdomain from string

      from urllib.parse import urlparse

      url = request.META['HTTP_HOST']

      parse = urlparse(url)

      print(parse.netloc.split('.')[0])