specify staticfiles to be loaded in every django template? - django

Is there a way to do {% load staticfiles %} automatically in every template file?
Would it significantly affect performance?
If it's a bad practice, I wonder if the following use-case is ok.
I'm *include*ing a file in a loop, and loading staticfiles,
{% for a in a_list %}
{% include "a.html" %}
{% endfor %}
a.html
{% load staticfiles %}
use {% static "a.html" %}

You can have the static tag automatically loaded into the set of default tag available in a template using the add_to_builtins method from template.base:
from django.template.base import add_to_builtins
add_to_buildins('django.templatetag.static')
This code would probably be best placed in your settings.py file, or anywhere else that gets imported automatically.

Related

Can I use {% static %} outside the base.html in Django?

I am a beginner in Django and i have setup a project with a base.html file along with the folder static/images/img.jpg.
base.html is setup correctly. Everything works inside this file but i have another file called index.html in the templates folder.
So, in other words in the base.html i can use the command {% static '/images/img. jpg' %} but in my index.html Django does not recognise the command.
In the index.html I have already provided the required commands {% extends 'base.html' %} and {% load static %}
Does this command work only in the base html? Do i need another command for files outside the base.html
Thank You
This command should work on every template file of Django, take a look if you are putting the code between a block {% block %} {% endblock %} or even if your IDE don't autocorrect it, run it and see if it works correctly

django-bootstrap3: changed theme_url but Bootswatch theme not loading?

I'm trying to use the bootswatch flatly theme. I followed the instructions given on the documentation regarding updating the settings.
I've added the following to my project's settings.py:
BOOTSTRAP3 = { 'theme_url': 'https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css', }
I've also added the following to my project's base.html template, between the head tags:
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
index.html template:
{% extends "base.html" %}
{% load i18n %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% block content %}
Hello World
{% endblock %}
However, the theme is not reflected when I reload my index page.
Is there something I'm doing wrong?
Edit: a temporary workaround I've found is to overwrite the css loaded by django-bootstrap3 by adding <link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css'> to the base.html template file, but I'd much prefer a solution using only django-bootstrap3.
Found out that this is a known issue, and has been fixed recently in the develop branch of the django-bootstrap repository. However, the pip package hasn't been updated yet.
Temporarily fixed this by editing my venv copy of django-bootstrap3.

Custom tag not loaded in template

I've created a custom tag that I want to use, but Django can't seem to find it. My templatetags directory is set up like this:
pygmentize.py
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from django import template
from pygments.formatters.other import NullFormatter
register = template.Library()
#register.tag(name='code')
def do_code(parser,token):
code = token.split_contents()[-1]
nodelist = parser.parse(('endcode',))
parser.delete_first_token()
return CodeNode(code,nodelist)
class CodeNode(template.Node):
def __init__(self,lang,code):
self.lang = lang
self.nodelist = code
def render(self,context):
code = self.nodelist.render(context)
lexer = get_lexer_by_name('python')
return highlight(code,lexer,NullFormatter())
I am trying to use this tag to render code in gameprofile.html.
gameprofile.html
(% load pygmentize %}
{% block content %}
<title>{% block title %} | {{ game.title }}{% endblock %}</title>
<div id="gamecodecontainer">
{% code %}
{{game.code}}
{% endcode %}
</div>
{% endblock content %}
When I navigate to gameprofile.html, I get an error:
Invalid block tag on line 23: 'code', expected 'endblock'. Did you forget to register or load this tag?
For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
For other versions use static
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
Also you have to check that you defined STATIC_URL in setting.py
At last, make sure the static files exist in the defined folder
The error is in this line: (% load pygmentize %}, an invalid tag.
Change it to {% load pygmentize %}
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
in your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE.
did you try this
{% load games_tags %}
at the top instead of pygmentize?
{% load static %}
Please add this template tag on top of the HTML or base HTML file
Encountered this same issue but I just added {% load static %} from my extends template and it worked. So in your case if you're trying to load gameprofile.html from a base template you just need to add it like this:
{% extends 'some_base.html' %}
{% block content %}
{% load pygmentize %}
I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:
Create a new Django app by executing: python manage.py startapp new_app
Edit the settings.py file, adding the following to the list of INSTALLED_APPS: 'new_app',
Add a new module to the new_app package named new_app_tags.
In a Django HTML template, add the following to the top of the file, but after {% extends 'base_template_name.html' %}: {% load new_app_tags %}
In the new_app_tags module file, create a custom template tag (see below).
In the same Django HTML template, from step 4 above, use your shiney new custom tag like so: {% multiply_by_two | "5.0" %}
Celebrate!
Example from step 5 above:
from django import template
register = template.Library()
#register.simple_tag
def multiply_by_two(value):
return float(value) * 2.0
The app that contains the custom tags must be in INSTALLED_APPS. So Are you sure that your directory is in INSTALLED_APPS ?
From the documentation:
The app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work. This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation.
In gameprofile.html please change the tag {% endblock content %} to {% endblock %} then it works otherwise django will not load the endblock and give error.
You need to change:
{% endblock content %}
to
{% endblock %}

What is the correct way of loading the static template tag in Django?

The documentation is a bit ambiguous..
In https://docs.djangoproject.com/en/dev/howto/static-files/#configuring-static-files it says
{% load staticfiles %}
and in https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#template-tags it says
{% load static from staticfiles %}
(some of our templates just have {% load static %} although I'm not sure if that is actually working..?)
Both ways are correct. But I always use {% load staticfiles %}.
{% static %} is the only tag in the staticfiles library so I don't see any reason to use the {% load static from staticfiles %} version.
As for the {% load static %} - this is a built-in template tag which has no relation with the staticfiles contrib app. If you don't use (and don't plan to use) any special STATICFILES_STORAGE then this version will work for you just fine.

Django - Dynamically include JS/CSS based on installed apps

Does anybody know a way to adjust the included JS/CSS resources in a template based on the apps you've installed?
Let's say we have a basic feature in app x using template.html, and this requires foo.js which is provided in the static files for the app.
What I'd like is a way of saying an additional and optional app y can register bar.js to be included in template.html as well and this provides some advanced functionality.
Ideally, this should be tied in on a feature level - so I register both foo.js and bar.js to provide for feature A and in my template I just indicate I want all the static content for A.
You can follow the django admin framework approach. In your base template have an extra section for style and javascript. Based on some condition you can insert the new files.
For Example:
Define these two blocks in your base template
{% block extracss %}{% endblock %}
{% block extrajs %}{% endblock %}
If you want to add a js or css based on some condition, you can add a check inside
{% block extracss %}
{% if new_app_installed %}
# Insert your CSS
{% else %}
# Default
{% endif %}
{% endblock %}
You can also check if your plugin app is installed and pass this context variable from view to template.
from django.conf import settings
if "new_app" in settings.INSTALLED_APPS:
is_new_app_installed = True