I'm using Django-instagram for simply display Instagram content on my webpage:
{% load instagram_client %}
{% instagram_user_recent_media intel %}
This example works perfect, but the problem is Instagram name changes depending on selected page. I pass it via context:
def about(request, foo_id):
article = get_object_or_404(Bar, id=foo_id)
return render_to_response('about.html', {'foo' : article})
It works fine if I'm using it without template:
<p>{{ foo.instagram }}</p> --> returns valid name
How can I pass my "foo.instagram" like this:
{% load instagram_client %}
{% instagram_user_recent_media {{ foo.instagram }} %}
You can use set:
{% set new_var = foo.instagram -%}
{% load instagram_client %}
{% instagram_user_recent_media new_var %}
Related
I have a django app with a basic model (Job). Now in my template I would like to check if an instance exists of that model or not. I want to project a text if there is nothing yet to show, otherwise I'd like to show the model attributes.
Somehow like so (which obviously doesn't work):
{% if job.title != "" %}
{{ job.title }}
{% else %}
hola
{% endif %}
Also tried:
{% for job in jobs %}
{% if job.title %}
{{ job.title }}
{% else %}
Hola
{% endif %}
{% endfor %}
It makes sense it doesn't work because how can I loop through it or return something if it doesn't exist. Is there a simple way to even do that in a template? Or do I have to write my own function? Or what would be a way to do that?
Help is of course very much appreciated
You can use the {% if %} tag. As Django doc says:
The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output.
So you can do something like this:
{% if job %}
{{ job.title }}
{% else %}
<p>Hi from Uruguay</p>
{% endif %}
If you need this inside a for, as #dirkgroten said, you need to use the {% empty %} tag. There is an example in the Django doc.
I have selected one column by using the peewee, and then send it to the template. But nothing return.
I have one table named Entry, with column tag_name.
#app.route('/archive')
def tag():
query_tag = (Entry.select(Entry.tag_name)).distinct())
return object_list('t.html', query_tag, check_bounds=False)
The corresponding template:
{%block content %}
{% for tag in object_list %}
<p>{{ tag }}</p>
{% endfor %}
{% endblock %}
And finally it display "None"
result_photo
But if I change to below code, it can work,:
#app.route('/archive')
def tag():
query_tag = (Entry.select().distinct())
return object_list('t.html', query_tag, check_bounds=False)
And the template:
{%block content %}
{% for tag in object_list %}
<p>{{ tag.tag_name }}</p>
{% endfor %}
{% endblock %}
You can combine your two examples and the following should work:
query_tag = Entry.select(Entry.tag_name).distinct()
And the template:
{% for entry in object_list %}
<p>{{ entry.tag_name }}</p>
{% endfor %}
Because, even though you've only selected one column, Peewee will still be returning Entry objects. The Entry objects will only have the "tag_name" field populated, though.
I'm new in Django and I am trying to search for something in a template if I find it a want to print something, if not I want to print something else.
sth like this:
{% for art in artifacts %}
{% if art.product_component == 'A' %}
<p> something.</p>
{{ found = True }}
{% endif %}
{% endfor %}
{% if not found %}
<p>NA</p>
{% endif %}
I know this is not the right way to do it, but this is just to understand the idea.
how can i do it?
You can write a templatetag for finding product_component == 'A' is exist or not.
your_app_dir/templatetags/product_tag.py
from django import template
from django.template import Library
register = Library()
#register.assignment_tag()
def check_product_component_status(artifacts):
value = [art for art in artifacts if art.product_component == 'A']
if value:
return True
return False
template:
{% for art in artifacts %}
{% if art.product_component == 'A' %}
<p> something.</p>
{% endif %}
{% endfor %}
{% load product_tag %}
{% check_product_component_status artifacts as status %}
{% if not status %}
<p> something.</p>
{% endif %}
I have two models: Site and Metric.
I want to display the Metric values alongside each Site.
My views.py is as follows:
from django.shortcuts import render
from .models import Site, Metric
def site_graph(request):
sites = Site.objects.order_by('name')
metrics = [s.metric_set.all() for s in sites]
return render(request, 'da/site_graph.html', {'sites': sites, 'metrics': metrics})
And my template content looks like this:
{% block content %}
{% for metric in metrics %}
[
{% for query in metric %}
{{ query.domain_authority }}
{{ query.date_queried }}
{% endfor %}
]
{% endfor %}
{% endblock content %}
I am not sure how I would go about getting the data I need in Django.
This data is going to be eventually passed onto d3.js for visualization which is why I need the data from the matching the primary key for each Site to be together.
You can use a list of dictionaries:
def site_graph(request):
metrics=[]
sites = Site.objects.order_by('name')
for site in sites:
metrics_site={}
metrics_site["site"] = site
metrics_site["metrics"] = site.metric_set.all()
metrics.append(metrics_site)
return render(request, 'da/site_graph.html', {'metrics': metrics})
And then in the template:
{% block content %}
{% for metric in metrics %}
{{ metric.site.name }}
{% for query in metric.metrics %}
{{ query.domain_authority }}
{{ query.date_queried }}
{% endfor %}
{% endfor %}
{% endblock content %}
metric.site.name is just an example if your model "site" contains a field "name" that you want to show.
I use:
DjangoCMS 2.4
Django 1.5.1
Python 2.7.3
I would like to check if my placeholder is empty.
<div>
{% placeholder "my_placeholder" or %}
{% endplaceholder %}
</div>
I don't want the html between the placeholder to be created if the placeholder is empty.
{% if placeholder "my_placeholder" %}
<div>
{% placeholder "my_placeholder" or %}
{% endplaceholder %}
</div>
{% endif %}
There is no built-in way to do this at the moment in django-cms, so you have to write a custom template tag. There are some old discussions about this on the django-cms Google Group:
https://groups.google.com/forum/#!topic/django-cms/WDUjIpSc23c/discussion
https://groups.google.com/forum/#!msg/django-cms/iAuZmft5JNw/yPl8NwOtQW4J
https://groups.google.com/forum/?fromgroups=#!topic/django-cms/QeTlmxQnn3E
https://groups.google.com/forum/#!topic/django-cms/2mWvEpTH0ns/discussion
Based on the code in the first discussion, I've put together the following Gist:
https://gist.github.com/timmyomahony/5796677
I use it like so:
{% load extra_cms_tags %}
{% get_placeholder "My Placeholder" as my_placeholder %}
{% if my_placeholder %}
<div>
{{ my_placeholder }}
</div>
{% endif %}
If you want additional content to be displayed in case the placeholder is empty, use the or argument and an additional {% endplaceholder %} closing tag. Everything between {% placeholder "..." or %} and {% endplaceholder %} is rendered in the event that the placeholder has no plugins or the plugins do not generate any output.
Example:
{% placeholder "content" or %}
There is no content.
{% endplaceholder %}
Here's a very compact solution.
Template filter:
#register.filter('placeholder_is_empty')
def placeholder_is_empty(request, slot):
page = request.current_page
placeholder = page.placeholders.get(slot=slot)
return placeholder.cmsplugin_set.exists()
Usage in template:
{% if request|placeholder_is_empty:'myplaceholder' %}
<h1>Here comes some content... </h1>
{% endif %}
Depending on what you are trying to achieve, you can simply use CSS to hide the element if doesn't have content using the :empty selector. And if you are worried about white spaces you can use Django's in-build {% spaceless %} template tag to remove them.
So you'd get this template:
{% spaceless %}
<div class="hide_if_empty">
{% placeholder "my_placeholder" %}
</div>
{% endspaceless %}
And this CSS:
hide_if_empty:empty {
display: none;
}
Not exactly what was asked for as it doesn't remove the HTML - but this will solve the most common case where one wants to check if a place holder is empty, and doesn't require the introduction of a new template tag.
Based on the great answer form #Philip Zedler, a solution that works for both placeholder on django-cms pages, but also on placeholders "outside of the cms".
#register.filter()
def placeholder_empty(page_placeholder, slot=None):
"""
for page/slot, pass a page object, and a slot name:
{% if request.current_page|djangocms_misc_placeholder_empty:"content" %}
for a outside page placeholder, just the placeholder object:
{% if object.placeholderfield|djangocms_misc_placeholder_empty %}
also, with:
{% with ph_empty=object.placeholderfield|djangocms_misc_placeholder_empty %}
"""
placeholder = None
if isinstance(page_placeholder, Placeholder):
placeholder = page_placeholder
elif isinstance(page_placeholder, Page):
page = page_placeholder
try:
placeholder = page.placeholders.get(slot=slot)
except Placeholder.DoesNotExist:
pass
if placeholder:
# // return not placeholder.cmsplugin_set.filter(language=get_language()).exists()
return not placeholder.cmsplugin_set.exists()
return False
usage in template
{% if request.current_page|placeholder_empty:'content' %}
<h1>Fallback!</h1>
{% endif %}
It's in my djangocms-misc package
I took the extra compact solution here and created a templatetag that checks if a static placeholder is not empty:
from cms.toolbar.utils import get_toolbar_from_request
#register.filter("static_placeholder_is_not_empty")
def static_placeholder_is_not_empty(request, slot):
placeholder = StaticPlaceholder.objects.get(code=slot)
if get_toolbar_from_request(request).edit_mode_active:
placeholder = placeholder.draft
else:
placeholder = placeholder.public
is_not_empty = len(placeholder.get_plugins(request.LANGUAGE_CODE)) > 0
return is_not_empty
It's used like this:
{% load my_new_shiny_templatetag %}
{% if request|static_placeholder_is_not_empty:'my_static_placeholder' %}
<div class="something">
{% endif %}
{% static_placeholder "my_static_placeholder" %}
{% if request|static_placeholder_is_not_empty:'my_static_placeholder' %}
</div>
{% endif %}