I try to replace default logo and title in a Wagtail app. According to http://docs.wagtail.io/en/v1.0b1/howto/custom_branding.html I've created templates/wagtailadmin/, have installed django-overextends and added overextends to my project’s INSTALLED_APPS object(base.py).
As a result is error Invalid block tag on line 1: 'overextends'. Did you forget to register or load this tag?
How can I correctly load overextends module to make it work? Any help appreciated. Thanks in advance.
See the overextends readme
In Django 1.9+, you must add overextends to the builtins key of your TEMPLATES setting
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'builtins': ['overextends.templatetags.overextends_tags'],
}
},
]
For most extensions which feature template tags, you need to load them in each template, e.g. {% load overextends_tags %}, but overextends is different, and in earlier versions of Django it self-adds to the builtins, see https://github.com/stephenmcd/django-overextends/blob/master/overextends/models.py
Note, Wagtail 1.0 is an old version, and the latest is 1.5.2. The Wagtail 1.5.2 Custom Branding documentation does detail the above template configuration step.
Update October 2016: Wagtail is now well past version 1.5. See #gasman's comment below for more.
Related
I followed this tutorial and integrated Django and VueJs using django-webpack-loader, now the main.js output from django-webpack-loader is loading to my index.html
This is my project directory structure
- assets
- bundles
- app.js
- js
- components
- Demo.vue
- index.js
- db.sqlite3
- manage.py
- myapp
- myproject
- node_modules
- package.json
- package-lock.json
- requirements.txt
- templates
- webpack.config.js
- webpack-stats.json
My Demo.vue component has been imported to the index.js and using webpack.config.js file all necessary file has been bundled together to app.js.
My question is what is the next step? For example, if I have some VueJs components and want to use them in some of my templates how should I do that? Should I create components in the component directory and bundle them all? If this is the case how should I choose to use or not use a component in a specific template? And how should I use Django template tags to insert dynamic data? Or I should write my components in another way?
I know there is multiple questions here, but I couldn't find a good reference to answer my questions so any help would be appreciated.
Django uses a templating language, called Jinja, to pass context (information) from view to template. Assuming that myapp is a Django app, you should have a myapp/views.py file by default.
In myapp/views.py, you have the ability to create a view (code that is run when a specific URL is accessed). For example, your view could look something like:
from django.shortcuts import render
def my_view(request):
context = {
'my_variable': 'my_variable_value',
}
return render(request, 'template.html', context)
Then, in template.html*, you can use Jinja to parse your context (access my_variable's value). Your template doesn't have to be an HTML file, it can be anything (JS, PHP, etc.), it's just the template file that's loaded from your view.
<html lang="en">
<head></head>
<body>
<h1>{{ my_variable }}</h1>
</body>
</html>
You can use Jinja with Javascript too:
<script>
function test() {
console.log({{ my_variable }});
}
</script>
Jinja supports a variety of functionality, including loops, if blocks, and custom functions (tags). Read more: https://codeburst.io/jinja-2-explained-in-5-minutes-88548486834e
If you're using static files that are NOT in your template file, you'll have to serve them as static files. This is a little more complicated, but not hard! You'll have to use a third party library for serving these files in production, like whitenoise. Here's a great tutorial for Django static files, as this extends past the scope of this question.
*Best practice is to make a directory myapp/templates and put template.html in that directory. Then, point Django to your templates folder in settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["myapp/templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
I am searching for a way to display my Django-CMS site name in a template.
I created a basic Django-CMS site following this guide. The default site is named Example.com and I was able to change this name, from within the admin section, to "My Super Site".
Following what, I tried to customize and apply a theme to it, following this guide. It suggests to use {{ request.site.name }} to display the name of the site on a page. However this turns up empty and so does {{ request.site }}.
I searched further and found several pages approaching the subject with increasingly complicated propositions the older they were. Recent ones, like this one, suggested that this was not related to django-cms but to django itself and the sites framework.
I looked into the documentation, particularly this page and this one which, if I understood properly, indicates that the site middleware, once activated, includes a site object in the request object available in the templates. I checked and the sites framework is enabled ('django.contrib.sites' in INSTALLED_APPS setting, SITE_ID defined and migrate ran). So, I don't understand why {{ request.site }} is empty.
To clarify things, I am not looking for the domain name or the host. I am looking for the user friendly name, the one found in django-cms under 'Display Name' in the 'Change site' section of administration/sites.
Thank you for your help.
make sure to add 'django.core.context_processors.request' to your context processors.
Like so:
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
'django.core.context_processors.request',
],
},
},
]
Also add django.contrib.sites.middleware.CurrentSiteMiddleware to your MIDDLEWARE settings.
For newer version of django ie.. >3, only adding
'django.contrib.sites.middleware.CurrentSiteMiddleware',
to the MIDDLEWARE in settings.py works. Then call
{{request.site.name}}
in your template.
I want a menu thats custom depending which group you are member of.
Im using Django 1.10.1, allauth and so on.
When im trying to make my templatetag it fails and it says:¨
TemplateSyntaxError at /
'my_templatetag' is not a registered tag library. Must be one of:
account
account_tags
admin_list
admin_modify
admin_static
admin_urls
cache
i18n
l10n
log
socialaccount
socialaccount_tags
static
staticfiles
tz
'my_templatetag.py' looks like this:
from django import template
from django.contrib.auth.models import Group
register = template.Library()
#register.filter(name='has_group')
def has_group(user, group_name):
group = Group.objects.get(name=group_name)
return group in user.groups.all()
and tha error comes in my .html file which say,
{% load my_templatetag %}
I have tried to restart the server like millions of times, also i tried to change all the names, and the app is a part of INSTALLED_APPS in settings.py.
What am I doing wrong?
Besides putting my_templatetag.py inside app_name/templatetags, make sure you restart the Django development server (or ensure it restarted itself) every time you modify template tags. If the server does not restart, Django won't register the tags.
From Django 1.9, you can load those new tags/filters in settings like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'app.apptemplates.load_setting',
],
'libraries':{
'my_templatetag': 'app.templatetags.my_templatetag',
}
},
},
]
If you have templatetag dir in your project dir (not in an app dir), then above method is recommended.
Example-
Quoting:
https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/#:~:text=It%20also%20enables%20you%20to%20register%20tags%20without%20installing%20an%20application.
Make sure you are not missing any of the following steps:
Create a folder called "templatetags" at the same level as models.py
and views.py in your application folder
Your application must be in the INSTALLED_APPS in settings.py
The templatetags folder must have __init__.py
Restart the django server
In my case the problem was, I was using {% load filter_method_name %}
I had to change to {% load filename %}
I then had to restart the server.
you have to manually stop the development server and start it again,
so Django can identify the new template tags
I am using Django 1.11, and I was having the same problem. Some of the answers here are right, but some things may be missing. Here is what I did:
Quoting a previous user:
Create a folder called "templatetags" at the same level as models.py
and views.py in your application folder
Your application must be in the INSTALLED_APPS in settings.py
The templatetags folder must have init.py
But, before you re-start the Django server, add this to the file that contains the tags:
from django import template
register = template.Library()
Then you can re-start the server.
Where is 'my_templatetag.py' stored? It should be stored in a directory called 'templatetags' which is within the app.
Please see: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
if that isn't the case.
Restart the django server. It worked for me after setting the templatetag folder within the app and template_name.py in the templatetag folder.
In case it helps someone, the issue in my case was that I was using quotes when trying to load the tag(s)
{% load 'my_templatetag' %} <!-- incorrect -->
instead of
{% load my_templatetag %} <!-- correct -->
Note: extends needs quotes around the filename but not load
I know this is a bit old, but I ran into the same problem today. I found the solution in the docs: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.
Simply copying the __init__.py from another location into the new templatetag's directory sorted it out.
I solved this by adding a templatestag folder in the root with a filter.py file defining my filters, then I adjusted my settings.py.
Please check my complete answer regarding this issue in this similar thread
put my_templatetag.py inside app_name/templatetags then create init.py inside app_name/templatetags .. Then open terminal in project folder give command python manage.py shell
from app_name.templatetags import my_templatetag
you just cut/remove your code which written inside the (example templatetags/home.py)
from home.py you remove your code and restart your server and again paste your code in home.py it will work.
The templatetags folder must have a __init__.py file in order to be a regular python package
Ensure that you also created the templatetags.py file next to the __init__.py file
For me, I had to register my customer Filter as this since my templatetags are outside of any app
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR, 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
# ! New Line
'libraries':{
'customFilter': 'templatetags.customFilter',
}
},
},
]
at first stop the server.remove/cut the code from templatetags/tag.py and rewrite/paste it.then run the server.it worked for me
Yah, This problem you are currently facing because of older django version Or Complexly to write "Depreciation"
if You HAve These Types OF TAgs In Your template/ Html Files Change Them With..
> {{% load staticfiles %} or {% load admin_static %}, {% load
> admin_static %}}
change with
{% load static %}
Get to The Point..
JUst SImply Perform These Replace All These from YOur BAse.html/or Any type Of HTML
I get a TemplateNotFound after I installed django-postman and django-messages. I obviously installed them separately - first django-postman, and then django-messages. This is so simple and yet I've spent hours trying to resolve this.
I'm using Django 1.8, a fresh base install using pip. I then installed the two above packages. The TEMPLATES portion of my settings.py file is as follows:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
#os.path.join(BASE_DIR, 'templates/django_messages'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Within my INSTALLED_APPS tuple, I've also installed the above packages as well.
Here's my addition to urls.py:
url(r'^messages/', include('django_messages.urls')),
No other changes were made to the system and yet when I go to /messages I get the following error message:
TemplateDoesNotExist at /messages/inbox/
django_messages/inbox.html
Request Method: GET
Request URL: http://localhost:8000/messages/inbox/
Django Version: 1.8.3
Exception Type: TemplateDoesNotExist
Exception Value:
django_messages/inbox.html
Exception Location: /projects/.virtualenvs/blatter/lib/python2.7/site-packages/django/template/loader.py in render_to_string, line 138
Python Executable: /projects/.virtualenvs/blatter/bin/python
Python Version: 2.7.6
The issue is because it extends from the site's base.html. It is also mentioned in postman documentation :- https://django-postman.readthedocs.org/en/latest/quickstart.html#templates
The postman/base.html template extends a base.html site template, in which some blocks are expected:
title: in <html><head><title>, at least for a part of the entire title string
extrahead: in <html><head>, to put some <script> and <link> elements
content: in <html><body>, to put the page contents
postman_menu: in <html><body>, to put a navigation menu
A possible solution can be found here :- django-postman extends a base.html that does not exist
The problem was resolved for django-messages after reviewing a called template and changing the extends/inheritance parameter.
The file that was being called, inbox.html, inherited "django_messages/base.html" ... which worked fine. "base.html" then inherited from "base.html," so there appeared to be some circular logic here causing the error. This is by default and wasn't added by me. When I removed the extends/inheritance declaration from "base.html" so that it didn't inherit from itself, django-messages worked.
Perhaps Django 1.8 changed some logic w/templates? Either way, issue resolved.
I want to use the static tag in templates like so:
<img src="{% static "img/test.jpg" %}">
I've found that that requires me to put
{% load static %}
at the beginning of every template file.
Since I'm using it everywhere, I would like it to be a globally available tag so I don't need to put {% load static %} to use it.
In my settings I do have:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.static',
)
I saw both of these questions:
Make django static tag globally available
and
Load a Django template tag library for all views by default
though neither seems to answer the question. In the former the question wasn't clear and in the later I get errors when I try to use:
from django.template.loader import add_to_builtins
add_to_builtins('django.core.context_processors.static')
Perhaps I'm not putting it in the correct location, or perhaps it's already part of the core so doesn't work?
How can I automatically get the static tag added into all template files without explicitly loading it for every file?
I think a lot of answers forget where you need to put the code. Well, let me start by telling you that you can use the following code to get the job done:
from django.template.loader import add_to_builtins
add_to_builtins('django.templatetags.static')
Now put this, in your main urls.py file. This worked for me.
Replace django.core.context_processors.static with django.templatetags.static:
>>> from django.template import Context,Template
>>> from django.template.loader import add_to_builtins
>>> add_to_builtins('django.templatetags.static')
>>> Template('{% static "img/test.jpg" %}').render(Context())
'/static/img/test.jpg'
BTW, your code has a typo: Replace add_to_bultins with add_to_builtins.
The answers are old and don't work in Django 3
in settings.py add 'django.templatetags.static' under TEMPLATES -> OPTIONS -> builtins
so with a basic default setup it should look like:
TEMPLATES = [
{
'BACKEND': ...,
'DIRS': ...,
'OPTIONS': {
'context_processors': [
...
],
'builtins': [
'django.templatetags.static',
],
},
},
]
thanks to a blog: https://chris-lamb.co.uk/posts/importerror-cannot-import-name-add_to_builtins-under-django-19