Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable django's TEMPLATE_STRING_IF_INVALID on a single method

Tags:

python

django

I've created a view that displays preview of other templates. I want to show the empty tags inside the templates, so I've included

TEMPLATE_STRING_IF_INVALID = '%s'

... on my settings.py file. However, I would only like to enable this setting for a particular view, not globally on my app.

Thanks in advance. :)

like image 895
rebelliard Avatar asked Nov 13 '22 01:11

rebelliard


1 Answers

from django.conf import settings

def myview(request):
    settings.TEMPLATE_STRING_IF_INVALID = '%s' # '%s' will get expanded to the variable name that was not found
    ...
    template = render(request, 'myview.html', {})
    settings.TEMPLATE_STRING_IF_INVALID = ''
    return template

Please note that this is ugly. If another user requests a different page in the short time before you reset the TEMPLATE_STRING_IF_INVALID back to '', then they might see invalid tags being displayed. The Django docs say specifically NOT to do this, but there is also an open ticket suggesting that it might be OK for some settings.

Hopefully someone smarter will come by and give a better solution.

like image 196
Vinod Kurup Avatar answered Dec 28 '22 07:12

Vinod Kurup