detect the HOST domain name in django models

筅森魡賤 提交于 2019-12-07 17:01:15

问题


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)


回答1:


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)



回答2:


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 .




回答3:


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


来源:https://stackoverflow.com/questions/1400500/detect-the-host-domain-name-in-django-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!