[Django]-Detect the HOST domain name in django models

2👍

If you’re calling the model method from a view, you could add a parameter for the request to the model method and include it when you call it from the view. E.g.

class MyModel(models.Model):
    ...
    def MyMethod(self, request):
        # Do whatever with request here

def MyView(request):
    mm = MyModel()
    mm.MyMethod(request)
👤Adam

1👍

You can also use ” request.get_host() ” method of HttpRequest to get the Domain name of the site this will return the originating host of the request using information from the HTTP_X_FORWARDED_HOST and HTTP_HOST headers and if dont provide value, The method will use the combination of SERVER_NAME and SERVER_PORT .

1👍

If the request object is unavailable, the best way is to use the Django Sites framework, I think. This requires having correctly set the site.domain (and site.name, if you want) beforehand. .get_current is set according to your django.conf.settings.SITE_ID.

>>> from django.contrib.sites.models import Site
>>> obj = MyModel.objects.get(id=3)
>>> obj.get_absolute_url()
'/mymodel/objects/3/'
>>> Site.objects.get_current().domain
'example.com'
>>> 'http://%s%s' % (Site.objects.get_current().domain, obj.get_absolute_url())
'http://example.com/mymodel/objects/3/'
👤Carl G

Leave a comment