Django: how to use {{ something }} inside css file - django

I have a model called Post with a FileField which is an image.
I want to do something like this:
.article-image{
background-image: url("../img/{{ post.postimage }});
}
but obviously it does not work, so I tried to make inline css instead:
<div class="article-image" style="background-image:{% static 'img/{{ post.postimage }}' %}"></div>
but it does not work too.
How can I fix this

for the first case you can't do that because it's CSS file not Django template.
but for the second case, you can use template tags like this
create templatetags/my_custom_tag.py in your app and add the following code into it.
from django import template
from your_base_app.settings import STATIC_URL
register = template.Library()
#register.simple_tag
def show_image(img):
return STATIC_URL + 'img/' + img;
you should load your tags in the top of your django template like that
{% load my_custom_tag %}
your django template should be like this
<div class="article-image" style="background-image:url({% show_image post.postimage.url %})"></div>

Related

how to use `url` template tag in `with` template tag in django templates

i have html component that i want to include in my template that has a link as below
<a href="{{url_name}}" ........
in my template i am trying to pass the url_name using the with tag
{% include 'components/buttons/_add_button.html' with url_name="{% url 'equipments:equipment-add' %}" reference_name='equipment' %}
this seems not to work as i get the following error
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: '"{%' from '"{%'
this works though
using the hardcoded url works however i wanted to implement this using url names for flexibility
{% include 'components/buttons/_add_button.html' with url_name="equipments/equipment/add" reference_name='equipment' %}
urls.py
app_name = "equipments"
....
path("equipment/add/",views.EquipmentCreateView.as_view(), name="equipment-add",
),
...
can i use a custom tag to pass this url name to my component template
I solved this by using a custom filter in Django as:
#register.filter
def get_url(url_name):
return reverse(url_name)
I now pass the url_name in my template as:
{% include 'components/buttons/_add_button.html' with url_name="equipments:equipment-add" reference_name='equipment' %}
Then in my Html component I use:
<a href="{{url_name|get_url}}"...

Dynamic Wagtail bgcolor templatetags

I am trying to get a dynamic background color with Wagtail templatetags when I convert an image like this :
{% load wagtailimages_tags %}
{% image my_file width-768 format-jpeg bgcolor-171721 as image_jpeg %}
<img src="{{ image_jpeg.url }}"/>
How I can change the value bgcolor-171721 with a dynamic variable in my template ?
I do not think it is possible to have dynamic token parts for a Django Template tag.
However, you could generate the rendition with the dynamic parts at the request (page model). The wagtail docs explain how to generate a rendition in Python. The tokens are similar but generated as one string separated by the | character.
You can then pass this into the template's context via your page model's `get_context' method.
models.py
class MyPage(Page):
# ...
def get_context(self, request):
# Update context to include an image rendition with a dynamic bg
context = super().get_context(request)
# https://docs.wagtail.io/en/stable/advanced_topics/images/renditions.html
some_dynamic_value = 'DDA0DD'
context['image_jpeg'] = self.my_image.get_rendition('width-768|bgcolor-%s|format-jpeg' % some_dynamic_value)
# you can use this within the template the same way - <img src="{{ image_jpeg.url }}"/>
return context
You could go further and create a custom template tag that takes a dynamic background colour (or reads it from the template context) but that might not be worth the extra complexity.

How do I use static files in a Django model's TextField?

I need to display static content inside of a model's TextField.
I have tried marking the TextField as safe in the template, but it doesn't seem to interpret it like the rest of the the template tags, only displaying it as raw HTML.
From my template:
{{ project.content|safe }}
From my model:
content = models.TextField()
From my view:
class ProjectView(generic.DetailView):
model = Project
context_object_name = "project"
template_name = "projects/project.html"
I'm expecting the content ({% static "wdv101/koala/index.html" %}) to display as a url to the static content, but instead it displays as {% static "wdv101/koala/index.html" %}
What you are trying to achieve is to use the string or project.content as template. Marking it as save means that e.g. Javascript is not escaped so that i will be executed.
You could solve your "problem" with a custom template tag that takes your content variable as input, renders it and returns the rendered html.
Custom template tag:
from django import template
from django.template import Template
from django.utils.html import mark_safe
register = template.Library()
#register.simple_tag(takes_context=True)
def in_template_renderer(context, template_string):
template = Template(template_string)
return mark_safe(template.render(context))
Using it in the template:
{% load in_template_renderer %}
{% in_template_renderer project.content %}
Do not forget to load required modules such as 'static' in your project.content.

django inclusion_tag

I'm trying to create inclusion tag and place it on the page but it's not work.
My views.py:
from django.shortcuts import render_to_response, redirect
from django import template
register = template.Library()
#register.inclusion_tag('weather.html')
def weather():
return {'city': 'angola'}
def home(request):
return render_to_response('index.html')
index.html
<title> TITLE </title>
Hi everyone!
{% weather %}
weather.html
weather is fine in {{city}}
Django debug page says that "Invalid block tag: 'weather'" so I guess I put declaration of inclusion_tag in wrong place? Where I need to put it to get it work?
Template tags need to go in a module in your app's templatetags directory. See the code layout section of the custom template tag docs for full details.
You then have to load your tag library in the template before you use your tag.
{% load my_tags %}
{% weather %}

Form labels not rendering with Django & WTForms

I'm trying to use WTForms with Django & a MongoEngine/MongoDB database backend. The forms are outputting properly, but I can't for the life of me get the labels to show up.
Here is my template code:
{% load wtforms %}
<form>
{% for f in form %}
{{ f.label }}: {% form_field f %}<br/>
{% endfor %}
</form>
This is what I am passing in the view:
form = StrandForm()
return render_to_response('create_strand.html', locals(), context_instance = RequestContext(request))
The StrandForm class I have tried both creating from the WTForm mongoengine extension's model_form class, and from WTForm's Form class. The label exists in the view, I can print it to the console and it shows the rendered form label, but somehow it gets lost when transferring to the template. Am I doing something wrong?
Django 1.4 has a new feature: do_not_call_in_templates attribute.
If you set it on wtforms.Field class, every child class inherits and all fields will work fine in django templates.
import wtforms
wtforms.Field.do_not_call_in_templates = True
Now following code works as expected:
{% load wtforms %}
{{ f.label }}: {% form_field f %}
I encountered the same problem today. It has to do with the way WTForms is programmed so that it will work with many different templating libraries. Django 1.3 will only see f as it's HTML string even though it has other attributes.
In order to fix this you must add a template tag to retrieve the attribute.
Add the following to your projects hierarchy:
templatetags
templatetags / init.py
templatetags / templatetags
templatetags / templatetags / init.py
templatetags / templatetags / getattribute.py
Then in your settings.py file, add the following line to INSTALLED_APPS
'templatetags',
Open up getattribute.py and paste the following code:
from django import template
from django.conf import settings
register = template.Library()
#register.tag
def getattribute(parser, token):
try:
tag_name, tag_object, tag_function = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires two arguments" % token.contents.split()[0])
return getattrNode(tag_object, tag_function)
class getattrNode(template.Node):
def __init__(self, tag_object, tag_function):
self.tag_object = tag_object
self.tag_function = tag_function
def render(self, context):
return getattr(context[self.tag_object], self.tag_function)()
This will allow you to use the follow code whenever you're inside a template and need an attribute that won't show up:
{% load getattribute %}
{% getattribute OBJECT ATTRIBUTE %}
In your case:
{% getattribute f label %}
Hope that helped!