Putting full URL link on email, how to get current domain name to put on url?

How do I get the current domain name on Django programmatically when sending email with URL to the website?

I tried this:

Added ‘django.contrib.sites’ on INSTALLED_APPS and ‘django.contrib.sites.middleware.CurrentSiteMiddleware’ on MIDDLEWARE

And then tried this:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()

But I get then following error:

django.core.exceptions.ImproperlyConfigured: You're using the Django "sites framework" without having set the SITE_ID setting. Create a site in your database and set the SITE_ID setting or pass a request to Site.objects.get_current() to fix this error.

How can I get current host programmatically in Django?

If this is something being done as a result of a request, you can get it from the Host header within the HttpRequest.

If this is something being looked for outside the context of a request, then you have to hard-code it somewhere. (e.g. Your settings file.)

There’s nothing within Django that “binds” a DNS entry to the application. (The Sites framework provides some facilities for segregating data and requests based on the submitted request, but you still need to configure what domains are going to be handled by your application.)

The current host may or may not have any relationship to the DNS name used to access your site. This is a completely different question.

Agree with Ken. I use an ENV var, as you can then use the same settings file in different environments such as dev, staging and prod.

# my settings file
import os
HOST = os.environ.get("HOST", default="http://localhost:8000/")