Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current domain name in Django template? [duplicate]

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 }}.

like image 564
Majoris Avatar asked Oct 30 '25 15:10

Majoris


1 Answers

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 }}.

like image 53
DevinG Avatar answered Nov 01 '25 05:11

DevinG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!