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?
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.)
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?