views:

265

answers:

3

Hi folks!

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)

+2  A: 

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
I'm officially stupid! Thanks, Adam! :) So I just need to use request.META['SERVER_NAME'] in that method, right? :) Again, Thanks a lot!
nadomado
That looks like the one you'd need.
Adam
A: 

Hi ,

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 .

Ansh J
A: 

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