Define HOST domain name in django models

In my model, I want to use the domain name (HOST), which I use in my views. In the views that can be executed thanks to the query object. But how do I do this? does it simulate methods? What doesn't use "HttpRequest" objects?

Now I set the global HOST value in settings.py and using it, but this is ugly.

In addition, I really do not want to manage the โ€œSitesโ€ (the โ€œSitesโ€ application). Is there any way I can capture the "default" hostname of the site?

Thank you very much for your help! (and sorry for my poor english)

+3
source share
3

, , . .

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

def MyView(request):
    mm = MyModel()
    mm.MyMethod(request)
+2

request.get_host() HttpRequest, , , HTTP_X_FORWARDED_HOST HTTP_HOST, , SERVER_NAME SERVER_PORT.

+1

request , - Django Sites, . site.domain ( site.name, ) . .get_current 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/'
+1

Source: https://habr.com/ru/post/1717267/


All Articles