nadomado
nadomado

Reputation: 51

detect the HOST domain name in django models

In my model, I want to use the domain name (HOST) I'm using in my views. In views that'd be doable, thanks to the "request" object. But how do I do this models methods? Which don't use "HttpRequest" objects?

Now I'm setting a global value HOST in settings.py and using it, but that's ugly.

Also, I don't really want to manage "Sites" (the Sites app) — Is there a way, I can grab the "by default" Site Host name?

Thanks a lot for your help! (and sorry for my poor English)

Upvotes: 3

Views: 3982

Answers (3)

Carl G
Carl G

Reputation: 18250

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/'

Upvotes: 1

Shreeyansh Jain
Shreeyansh Jain

Reputation: 1495

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 .

Upvotes: 1

Adam
Adam

Reputation: 7207

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)

Upvotes: 2

Related Questions