Django: Obtaining the absolute URL without access to a request object

后端 未结 2 470
暖寄归人
暖寄归人 2021-02-07 03:34

I have a model like the one below. When an instance is created, I want to send out an e-mail to an interested party:

class TrainStop(models.Model):
    name = mo         


        
相关标签:
2条回答
  • 2021-02-07 04:01

    For getting current site there's object Site:

    If you don’t have access to the request object, you can use the get_current() method of the Site model’s manager. You should then ensure that your settings file does contain the SITE_ID setting. This example is equivalent to the previous one:

    from django.contrib.sites.models import Site
    
    def my_function_without_request():
        current_site = Site.objects.get_current()
        if current_site.domain == 'foo.com':
            # Do something
            pass
        else:
            # Do something else.
            pass
    

    More info: http://docs.djangoproject.com/en/dev/ref/contrib/sites/

    0 讨论(0)
  • 2021-02-07 04:22

    There's the sites framework, as yedpodtrzitko mentioned, but, as you mentioned, it's very much a manual setup.

    There's requiring a setting in settings.py, but it's only slightly less manual than setting up sites. (It can handle multiple domains, just as well as sites and the SITE_ID setting can).

    There's an idea for replacing get_absolute_url, that would make stuff like this easier, though I think its implementation suffers from the same problem (how to get the domain, scheme [http vs https], etc).

    I've been toying with the idea of a middleware that examines incoming requests and constructs a "most likely domain" setting of some sort based on the frequency of the HTTP HOST header's value. Or perhaps it could set this setting on each request individually, so you could always have the current domain to work with. I haven't gotten to the point of seriously looking into it, but it's a thought.

    0 讨论(0)
提交回复
热议问题