How to display the site's user friendly name in a template in Django?
Asked Answered
N

2

9

I am searching for a way to display my Django-CMS site name in a template.

I created a basic Django-CMS site following this guide. The default site is named Example.com and I was able to change this name, from within the admin section, to "My Super Site". Following what, I tried to customize and apply a theme to it, following this guide. It suggests to use {{ request.site.name }} to display the name of the site on a page. However this turns up empty and so does {{ request.site }}.

I searched further and found several pages approaching the subject with increasingly complicated propositions the older they were. Recent ones, like this one, suggested that this was not related to django-cms but to django itself and the sites framework.

I looked into the documentation, particularly this page and this one which, if I understood properly, indicates that the site middleware, once activated, includes a site object in the request object available in the templates. I checked and the sites framework is enabled ('django.contrib.sites' in INSTALLED_APPS setting, SITE_ID defined and migrate ran). So, I don't understand why {{ request.site }} is empty.

To clarify things, I am not looking for the domain name or the host. I am looking for the user friendly name, the one found in django-cms under 'Display Name' in the 'Change site' section of administration/sites.

Thank you for your help.

Naval answered 25/3, 2017 at 21:42 Comment(0)
L
13

make sure to add 'django.core.context_processors.request' to your context processors.

Like so:

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'django.core.context_processors.request',
            ],
        },
    },
]

Also add django.contrib.sites.middleware.CurrentSiteMiddleware to your MIDDLEWARE settings.

Lawford answered 25/3, 2017 at 23:52 Comment(4)
Thank you for your comment @Paulo. However this context processor is already in place.Naval
@Naval I've updated my answer to include the site middleware.Lawford
Well @Lawford that Sir, did the trick! At least the expected name seems to appear now. Thanks a lot!Naval
django.core.context_processors.request was moved to django.template.context_processors.request in Django 1.10.Erleena
C
1

For newer version of django ie.. >3, only adding

'django.contrib.sites.middleware.CurrentSiteMiddleware',

to the MIDDLEWARE in settings.py works. Then call

{{request.site.name}}

in your template.

Caseycash answered 20/7, 2020 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.