Django Template Conditional Statement Using Dates - python

I'm trying to do a check on my Django template to see if the 'date_added' field for a particular post is within the last three days.
I'm trying something like this:
{% for deal in deals %}
{% if deal.date_added > (timezone.now ()- timezone.timedelta(days=4)) %}
<h1>HOT</h1>
{% else %}
do some other stuff
{% endif %}
{% endfor %}
I'm getting this error: Could not parse the remainder: '(timezone.now' from '(timezone.now'
so something tells me deep inside that this is absolutely not possible to have this sort of conditional statement run from within the template---but figured i'd check. thanks.

class Deal(models.Model):
...
def get_label(self):
if self.date > datetime.date.today() - datetime.timedelta(days=4):
return "<h1>HOT</h1>"
else:
return "OLD..."
... then in your template
{% for deal in deals %}
{{ deal.get_label | safe }}
{% endfor %}

Related

Is there a way to output just the first element in this if statement, Django template?

In my table and in the some record I have lot of link_img, but I want only the first link_img, what can I do ?
I have something like this in my temp
{% for link in sousimg %}
{% if article.article_img.id == link.img_link.id %}
{{ link.link_img }}
{% endif %}
{% endfor %}
This type of question is already present so I suggest having a look at it.
django for loop counter break
You have to do a little bit of hit and trial in this case.

Creating a custom template tag to replace the for loop - Django

I am trying to simplify my code by creating a custom template tag for a 'for loop' that use frequently on my Django web application. I thought it would be a simple straight process, but something isn't working right... I can use some assistance in catching my error.
Here is my code.
views.py
class ArticleView(DetailView):
model = Articles
def get_context_data(self, **kwargs):
context = super(ArticleView, self).get_context_data(**kwargs)
context['s_terms'] = scientific_terms.objects.all()
return context
template tag
#register.filter(name='term')
def term(value):
{% for term in s_terms %}
{{ term.short_description }}
{% endfor %}
template.html
{% Neurons|term %}
Thank you for your assistance, in advance.
You are mixing Python code with the Django Template Language. The template tags are plain Python code, as they are defined inside a Python module. A working example would be:
#register.filter(name='term')
def term(terms):
output = ''
for term in terms:
output = '{0} {1}'.format(output, term.short_description)
return output
Then you could use it like this:
{{ s_terms|term }}
Maybe what you want is simply to create a reusable Django template.
For example, create a new template named terms.html:
templates/terms.html
{% for term in terms %}
<p>{{ term.short_description }}</p>
{% endfor %}
Then, in another template, you could include this partial template:
templates/index.html (name is just an example)
{% extends 'base.html' %}
{% block content %}
<h1>My application</h1>
{% include 'terms.html' with terms=s_terms %}
{% endblock %}

Breaking template on {% load rango_template_tags %}

So I am half way through a tutorial useing the book Tango With Django trying desperately hard to take on as much information as i can about Django.
Now i am trying to set up a template that lists all the category's but i get an error
invalid syntax (rango_template_tags.py, line 8)
I have no idea why i am getting this line, absolutely none i have checked it with the book 5 + times but i cant find anything that looks out of place of wrong. Can anyone please tell me why i am getting this error.
Base.html
{% load rango_template_tags %}
<div>
{% block sidebar_block %}
{% get_category_list %}
{% endblock %}
</div>
# This file has more within it these are the new pieces of code that break the template system. If these are in it wont work.
rango_template_tags
from django import template
from rango.models import Category
register = template.Library()
#register.inclusion_tag('rango/cats.html')
def get_category_list():
return {'cats' Category.objects.all()}
cats.html
<ul>
{% if cats %}
{% for c in cats %}
<li>{{ c.name }}</li>
{% endfor %}
{% else %}
<li><strong> There ar eno categories presen. </strong></li>
{% endif %}
</ul>
In python dictionary, each key is separated from its value by a colon (:)
Change your return statement from {'cats' Category.objects.all()} to {'cats': Category.objects.all()} and code within function or block should be idented.
from django import template
from rango.models import Category
register = template.Library()
#register.inclusion_tag('rango/cats.html')
def get_category_list():
return {'cats': Category.objects.all()}

flask and wtf - how can I direct tag attributes for fields?

After fiddling with wtforms, fields use widgets to actually render them to html. I wrote some custom field/widget to draw html in a way that I'd more like to. But here's a question:
suppose I want to render them with pre-defined css class or give actual details myself.
How can I achieve this? and on what phase of handling requests(at Form class declaration? or when setting attributes to give Form some Fields? or when I'm actually calling them in jinja2 templates) I should do that?
I use a Jinja macro something like this:
{% macro field_with_errors(field) %}
{% set css_class=kwargs.pop('class', '') %}
{% if field.type in ('DateField', 'DateTimeField') %}
{{ field(class='date ' + css_class, **kwargs) }}
{% elif field.type == 'IntegerField' %}
{{ field(class='number ' + css_class, **kwargs) }}
{% else %}
{{ field(class=css_class, **kwargs) }}
{% endif %}
{% if field.errors %}
<ul class="errors">{% for error in field.errors %}<li>{{ error|e }}</li>{% endfor %}</ul>
{% endif %}
{% endmacro %}
usage is something like:
{{ field_with_errors(form.foo, placeholder='bar') }}
This lets me avoid boilerplate, but also lets me keep the display decisions in the template space.
Have a look at the rendering fields section.
Alternatively, you can add attributes to be rendered in the Jinja2 (etc.) template:
<div class="input-prepend">
{{ form.address(placeholder="example.com", id="address", autofocus="autofocus", required="required") }}
</div>
There's nothing to prevent you from using a variable for the ID value above, instead of address, then rendering the template with a keyword argument to populate it.

What are some useful non-built-in Django tags?

I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a template tag that would have saved me time and ugly code.
So what are some useful template tags that doesn't come built into Django?
I'll start.
http://www.djangosnippets.org/snippets/1350/
Smart {% if %} template tag
If you've ever found yourself needing more than a test for True, this tag is for you. It supports equality, greater than, and less than operators.
Simple Example
{% block list-products %}
{% if products|length > 12 %}
<!-- Code for pagination -->
{% endif %}
<!-- Code for displaying 12 products on the page -->
{% endblock %}
smart-if. Allows normal if x > y constructs in templates, among other things.
A better if tag is now part of Django 1.2 (see the release notes), which is scheduled for release on March 9th 2010.
James Bennet's over-the-top-dynamic get_latest tag
edit as response to jpartogi's comment
class GetItemsNode(Node):
def __init__(self, model, num, by, varname):
self.num, self.varname = num, varname
self.model = get_model(*model.split('.'))
self.by = by
def render(self, context):
if hasattr(self.model, 'publicmgr') and not context['user'].is_authenticated():
context[self.varname] = self.model.publicmgr.all().order_by(self.by)[:self.num]
else:
context[self.varname] = self.model._default_manager.all().order_by(self.by)[:self.num]
return ''
<div id="news_portlet" class="portlet">
{% get_sorted_items cms.news 5 by -created_on as items %}
{% include 'snippets/dl.html' %}
</div>
<div id="event_portlet" class="portlet">
{% get_sorted_items cms.event 5 by date as items %}
{% include 'snippets/dl.html' %}
</div>
I call it get_sorted_items, but it is based on James' blog-post
In come case {% autopaginate queryset %} (http://code.google.com/p/django-pagination/) is useful. For example:
#views.py
obj_list = News.objects.filter(status=News.PUBLISHED)
# do not use len(obj_list) - it's evaluate QuerySet
obj_count = obj_list.count()
#news_index.html
{% load pagination_tags %}
...
# do not use {% if obj_list %}
{% if obj_count %}
<div class="news">
<ul>
{% autopaginate obj_list 10 %}
{% for item in obj_list %}
<li>{{ item.title }}</li>
{% endfor %}
</ul>
</div>
{% paginate %}
{% else %}
Empty list
{% endif %}
Note, that obj_list must be lazy - read http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1

Categories