Question

How to get the current domain name in Django template?

How to get the current domain name in Django template? Similar to {{domain}} for auth_views. I tried {{ domain }}, {{ site }}, {{ site_name }} according to below documentation. It didnt work.

<p class="text-right">&copy; Copyright {% now 'Y' %} {{ site_name }}</p>

It can be either IP address 192.168.1.1:8000 or mydomain.com

https://docs.djangoproject.com/en/5.0/ref/contrib/sites/

In the syndication framework, the templates for title and description automatically have access to a variable {{ site }}, which is the Site object representing the current site. Also, the hook for providing item URLs will use the domain from the current Site object if you don’t specify a fully-qualified domain.

In the authentication framework, django.contrib.auth.views.LoginView passes the current Site name to the template as {{ site_name }}.

 4  51  4
1 Jan 1970

Solution

 3

You can add it into your context through your view. Here's an example if you were to use a generic TemplateView:

views.py

from django.views.generic import TemplateView
from django.contrib.sites.shortcuts import get_current_site

class SomeView(TemplateView):
    template_name = "path/to/template.html"

    def get_context_data(self, **kwargs):
        current_site = get_current_site(self.request)
        
        context = super().get_context_data(
            **kwargs,
            domain = current_site.domain
        )
        return context

Then you would be able to reference domain as a template variable in your template: {{ domain }}.

2024-07-03
DevinG

Solution

 1

You can use {{ request.get_host }}

2024-07-03
Puzzleshock