Adding attributes to base.html BODY tag from child template


I am new to Python and Django so please forgive me if I am asking a dumb question but I am wondering if it is possible to add and attribute to the BODY tag from a child template. I am developing a project where the login page will have a background graphic but other than that it can have the same base template as all the other pages. To do that I want to add a class attribute to the BODY tag but not sure how to do it, if indeed it is possible. I don’t think using super. works as BODY is outside of the block.

If I can’t do it then I guess the alternatives would be to use a div inside my login template or perhaps another dedicated template for login but I wanted to keep all my nav bar code without having to replicate it.

What’s the best practice design pattern for this type of requirement?

Thanks very much


You don’t add to the template from a child template. The “parent” template is rendered with the same context as the child template extending it.
This means that you can include a context variable in your base template, and it will be rendered with the current context.
(Also remember that templates don’t throw errors if a variable doesn’t exist, so if you add a variable to your BODY tag, it’s ok if not every page defines something for it.)


Thanks for the reply Ken.

So basically I would need to put something like " in the base.html and then in the view for the login page have something like

from django.template.response import TemplateResponse

def login(request, template_name="myapp/login.html"):
    args = {}
    class = "loginBackground"
    args['myclass'] = class
    return TemplateResponse(request, template_name, args)

Or is it even more simple?

Unfortunately, you didn’t ‘escape’ the HTML in your first sentence, so I can only assume that what you wrote is correct.

But yes, if your parent template had something like:
<div class="{{ myclass }}">, then that would work.

If you prefer more terse code, you could even do this:

def login(request, template_name="myapp/login.html"):
    return TemplateResponse(
        request, template_name, {'myclass': "loginBackground"}
1 Like

Yes - sorry for lack of escaped code but it was essentially what you wrote.

Very helpful!