Custom tag not loaded in template - django

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 %}

Related

How to add a logo to the site index bar using django

Can anyone help me on how to add a logo to the index bar in Django-admin site?
You should probably override (by extend) the app_index.html admin template.
https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model
So you need to create a template/admin directory in your application and override the correct template by adding you own logo.
[Edit]
Oh sorry, you screenshot was too small and I just realized that you’re talking about the icon in the tabbar. That would be the favicon. For that, it’s simple, just add a favicon.ico into your static/ folder, and serve that directly from your http server (probably with a alias).
You can also serve the file directly using a simple view, but that doesn’t seems like a good idea except in development.
Your Question is answered here.
You have to override Django base.html template and put it under the admin directory.
https://stackoverflow.com/a/44428576/7122788
Override the Django base.html template and put it under the admin directory like my_app/templates/admin/base.html
Add {% block extrahead %} to the overriding template.
{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
{{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>
{% endblock %}
{% block extrahead %}
<link rel="shortcut icon" href="{% static 'favicon.ico' %}" />
{% endblock %}
{% block stylesheets %}
{{ block.super }}
{% endblock %}

Django load specific javascript file

I would like to load a specific javascript file for the specific html file. Instead of loading them into the base.html. Then a lot of pages will have unnecessary scripts that are not used.
I get this error:
Invalid block tag on line 3: 'static', expected 'endblock'. Did you forget to register or load this tag?
when i try to load it into the child.html. I'm
{% extends 'base.html' %}
{% block js %}
<script src="{% static "javascript/week.js" %}" type="text/javascript"></script>
{% endblock %}
You need to do {% load static %} in any template file that uses the {% static %} tag.

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.

Django 1.5: adminmedia and django-filebrowser-no-grappelli

I try to use django-filebrowser-no-grappelli with Django 1.5.
The prodlem is:
In Django 1.5 the template tags library adminmedia, which only contained the deprecated template tag {% admin_media_prefix %}, was removed.
Django-filebrowser-no-grappelli use adminmedia in templates:
{% adminmedia %}
<link rel="stylesheet" type="text/css" href="{% custom_admin_media_prefix %}css/forms.css" />
How can I fix it? Thx!
Ok,
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
.....
'django.core.context_processors.static',
)
Then change all {% adminmedia %} on {% static %}, {% custom_admin_media_prefix %} on {{ STATIC_URL }}.
Add quotes to all {% url 'someting' %} (new syntax in 1.5). Maybe it's not absolutely correct, but it's working.
But, I can't add filebrowser to the TinyMCE :( Why?
See, {% url %} tag had some disadvantage in syntax: when you typing {% url app.views.view %} it can be read in two ways:
You have your view function in app.views
You have variable or object 'app' with method or key or property called 'views' and 'view' inside it.
It was ambiguous so since django 1.5 you should define your view location like a string:
{% url 'app.views.view' %}.
BTW, i think there is no fork of django-filebrowser-no-grappelli with support django 1.5. I hope it will be soon

Overriding admin css in django

I want to change certain css in admin django like base.css. Is it better to change directly in the django library? How can I override it in the best way?
It depends a lot of what you want to do. Though first of all: do not overwrite it in the Django admin directly. You got two options I think are reasonable:
If you want to change the appearance of the admin in general you should override admin templates. This is covered in details here: Overriding admin templates. Sometimes you can just extend the original admin file and then overwrite a block like {% block extrastyle %}{% endblock %} in django/contrib/admin/templates/admin/base.html as an example.
If your style is model specific you can add additional styles via the Media meta class in your admin.py. See an example here:
class MyModelAdmin(admin.ModelAdmin):
class Media:
js = ('js/admin/my_own_admin.js',)
css = {
'all': ('css/admin/my_own_admin.css',)
}
In settings.py, make sure your app is listed before admin in the INSTALLED_APPS.
Create (your-app)/templates/admin/base_site.html and put the <style> block into the {% block extrahead %}
Example:
{% extends "admin/base_site.html" %}
{% block extrahead %}
<style>
.field-__str__ {
font-family: Consolas, monospace;
}
</style>
{% endblock %}
This solution will work for the admin site, I think it's the cleanest way because it overrides base_site.html which doesn't change when upgrading django.
Create in your templates directory a folder called admin in it create a file named base_site.html.
Create in your static directory under css a file called admin-extra.css .
Write in it all the custom css you want for your forms like: body{background: #000;}.
Paste this in the base_site.html:
{% extends "admin/base.html" %}
{% load static from staticfiles %} # This might be just {% load static %} in your ENV
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "css/admin-extra.css" %}" />{% endblock %}
{% block branding %}
<h1 id="site-name">{{ site_header|default:_('Django administration') }}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
As mentioned in the comments:
make sure your app is before the admin app in INSTALLED_APPS, otherwise your template doesn't override django's
That's It! you're done
I just extended admin/base.html to include a reference to my own css file - at the end. The beauty of css is that you don't have to touch existing definitions, just re-define.
In your static directory, create a static/admin/css/base.css file.
Paste in Django's default Admin CSS first, then add your customizations at the bottom.
If you want a global scope and you don't want to think about overriding templates a mixin works really well for this. Put this code wherever you want:
class CSSAdminMixin(object):
class Media:
css = {
'all': ('css/admin.css',),
}
Then, make a CSS file called admin.css with your overrides, for example:
select[multiple] {
resize: vertical;
}
Then, in whatever models you want, do:
class MyModelAdmin(admin.ModelAdmin, CSSAdminMixin):
And you'll be all set.
Have admin/css/changelists.css inside a folder in STATICFILES_DIRS, and it will user that changelists.css instead of the default admin one.
It just so happens that using <style> tag inside {% block extrastyle %}{% endblock %} did not work for me when I wanted to override css. Theming support provides the correct way. All I was missing is {{ block.super }} :-
{% extends 'admin/base.html' %}
{% block extrastyle %}{{ block.super }}
<style>
--- your style ---
--- properties here ---
</style>
{% endblock %}