How do I detect the current domain name in django?

Question:

I want to design my web application to serve two different front-end templates depending on what domain the user enter my django application.

So, if the user enter aaa.com, it would serve front-end from app AAA_USA, but if the user enter from aaa.co.my, it would serve front-end from app AAA_MY.

What is the best way to do this? I was thinking of "detecting the current domain name" and then simply add an if-else statements in the View functions.

These two domains will be pointing to the same Nameservers that contains my Django app.

Asked By: Raymond Seger

||

Answers:

Use

request.build_absolute_uri()

will retrive the full path:
es:

http://localhost:8000/test/

Answered By: Mattia

The way i did it is basically using the middleware (using session and detect the HTTP_HOST.

class SimpleMiddleware(object):
def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.

def __call__(self, request):
    # Code to be executed for each request before the view (and later middleware) are called.

    # sets to show Taiwan or Indo version
    # sets the timezone too
    http_host = request.META['HTTP_HOST']
    if(http_host == 'http://www.xxx.tw'):
        request.session['web_to_show'] = settings.TAIWAN
        request.session['timezone_to_use'] = settings.TAIWAN_TIMEZONE
    else:
        request.session['web_to_show'] = settings.INDO
        request.session['timezone_to_use'] = settings.INDONESIA_TIMEZONE

    response = self.get_response(request)

    # Code to be executed for each request/response after the view is called.

    return response
Answered By: Raymond Seger

If you don’t have access to the requests object, then you can use the sites framework:

from django.contrib.sites.shortcuts import get_current_site
domain = get_current_site(None)

This will return the site the Django is configured for (using the value saved in the django_site table of your database. (See: https://docs.djangoproject.com/…/sites/shortcuts/)

Answered By: SumYungGuy

You can get a full url with "build_absolute_uri()":

def myview(request):
    request.build_absolute_uri()
    # http://localhost:8000/admin/store/product/

Then, this below can get the url without "admin/store/product/":

def myview(request):
    request.build_absolute_uri('/')
    # http://localhost:8000/

Then, this below can get the url without "/admin/store/product/":

def myview(request):
    request.build_absolute_uri('/')[:-1]
    # http://localhost:8000
Answered By: Kai – Kazuya Ito