Django Diff between Dates - django

I have a project in django and i am trying to render html to pdf.
I'm trying to build a table, and i have two varaibles date1 and date2 and i need to do a Diff between date1 and date2.
If the result is more than 20 woriking days show 1 if not show 0
MY HTML
{% for item in obj %}
<tr>
<td>
{% if item.date1 - item.date2 > 20 %}
1
{% else %}
0
{% endif %}
</td>
</tr>
{% endfor %}

You can add a method in the model to calculate difference, then use it in the templates/pdf. For example:
class SomeView(models.Model):
# .. fields
def date_diff(self):
diff = self.date1 - self.date2 # returns time delta object
return abs(diff.days)
And use it in template:
{% for item in obj %}
<tr>
<td>
{% if item.date_diff > 20 %}
1
{% else %}
0
{% endif %}
</td>
</tr>
{% endfor %}

you should perform the calculation in the backend and send number of days value while rendering the template
difference=item.date1-item.date2
days=difference.days
and in template
{% if days > 20 %}
1
{% else %}
0
{% endif %}

Related

Jinja change variable value in IF condition

I need to create a table one row and one row
so I wrote following code in template file ;
{% for dict_item in sonuc %}
{% if dict_item.status ==0 %}
{% if count == 1 %}
<tr>
{% set count = 0 %}
{% elif count == 0 %}
<tr class="alt">
{% set count = 1 %}
{% endif %}
<td>{{ dict_item.zaman }}</td><td>{{ dict_item.saat }}</td><td>{{ dict_item.kad }}</td><td>{{ dict_item.mak }}</td><td>{{ dict_item.uyg }}</td> </tr>
{% elif dict_item.status ==1 %}
{% if count == 1 %}
<tr>
{% set count = 0 %}
{% elif count == 0 %}
<tr class="alt">
{% set count = 1 %}
{% endif %}
<td><b>{{ dict_item.zaman }}</b></td><td><b>{{ dict_item.saat }}</b></td><td><b>{{ dict_item.kad }}</b></td><td><b>{{ dict_item.mak }}</b></td><td><font color="red"><b>{{ dict_item.uyg }}</b></font></td> </tr>
{% endif %}
{% endfor %}
but not change count value so all rows created with
<tr class="alt"> tag
as I think I 'm choose the wrong method for solution
I don't understand why I can't change the value of the" content " variable in if condition.
The Jinja2 cycle method is what you're looking for. There's an example in the docs. Note that one of the values in the cycle arguments can be an empty string.

Django 2.2 How to disable checkboxes in list view

Django 2.2
I have a list view controlled by admin.py class. No custom template, all default. I can control what fields from the table should be shown in the view with this:
fields = ('myfield1','myfield2', ...).
Each row in the list table has a checkbox in the first column, the source looks like this:
<td class="action-checkbox">
<input type="checkbox" name="_selected_action" value="123" class="action-select">
</td>
My questions are:
How to disable those checkboxes (preferably, from Django code, without introducing a custom template) ?
Can it be done for SOME of the checkboxes (let's say I have a list of pk ids for the rows I don't want to see checkboxes.)
You can delete Items with those CheckBoxes, but if you want to customize your own admin page to override it
You can use this doc https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#admin-overriding-templates
This question is 2 years old now, but for the case someone still needs it, the following code works to overwrite the change-list_results.html:
{% load i18n static %}
{% if result_hidden_fields %}
<div class="hiddenfields">{# DIV for HTML validation #}
{% for item in result_hidden_fields %}{{ item }}{% endfor %}
</div>
{% endif %}
{% if results %}
<div class="results">
<table id="result_list">
<thead>
<tr>
{% for header in result_headers %}
{% if "checkbox" in header.text %}
{% else %}
<th scope="col" {{ header.class_attrib }}>
{% if header.sortable %}
{% if header.sort_priority > 0 %}
<div class="sortoptions">
<a class="sortremove" href="{{ header.url_remove }}" title="{% translate "Remove from sorting" %}"></a>
{% if num_sorted_fields > 1 %}<span class="sortpriority" title="{% blocktranslate with priority_number=header.sort_priority %}Sorting priority: {{ priority_number }}{% endblocktranslate %}">{{ header.sort_priority }}</span>{% endif %}
</div>
{% endif %}
{% endif %}
<div class="text">{% if header.sortable %}{{ header.text|capfirst }}{% else %}<span>{{ header.text|capfirst }}</span>{% endif %}</div>
<div class="clear"></div>
{% endif %}
</th>{% endfor %}
</tr>
</thead>
<tbody>
{% for result in results %}
{% if result.form and result.form.non_field_errors %}
<tr><td colspan="{{ result|length }}">{{ result.form.non_field_errors }}</td></tr>
{% endif %}
<tr>
{% for item in result %}
{% if "_selected_action" in item %}
{% else %}
{{ item }}
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
It stops stops the output of the for loops if theres a checkbox in there. --> It just removes the checkboxes.

Django template integer value iteration

I have the following model
class Table(models.Model):
# Some not important attrs
rows = IntegerField(etc)
cols = IntegerField(etc)
Then I have my view where I'm rendering objects of this model. And I need to build some HTML tables based on the quantity of each objects' rows and cols.
View:
get_tables(request):
tables = Table.objects.all()
return render(request, 'tables.html', {'tables': tables})
I'm trying to do something like:
{% for table in tables %}
<table>
<thead>
<tr>
{% for col in table.cols %}
<th>column label here</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in table.rows %}
<tr>my row</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
I know it is possible to loop for key in dict. But the values cols and rows are integers. How can I achieve this on a Django template?
Try
{% for table in tables %}
<table>
<thead>
<tr>
{% with ''|center:table.cols as range %}
{% for _ in range %}
<th>column label here</th>
{% endfor %}
{% endwith %}
</tr>
</thead>
<tbody>
{% with ''|center:table.rows as range %}
{% for _ in range %}
<tr>my row</tr>
{% endfor %}
{% endwith %}
</tbody>
</table>
{% endfor %}
# You can take use of filter tags in django template
# For Example
Step 1:- Create 'templatetags' package in your app folder.
Step 2:- Create filter.py in 'templatetags' package
Step 3:-
from django import template
register = template.Library()
def table_rows(value):
value_list = [value]
html_row = ''
for val in value_list:
html_row += '<tr></tr>'
return html_row
def table_cols(value):
value_list = [value]
html_cols = ''
for val in value_list:
html_cols += '<td>Hello</td>'
return html_cols
register.filter('table_rows', table_rows)
register.filter('table_cols', table_cols)
Step 4:-
# Your template can be:-
{% load filter %}
{% for table in tables %}
<table border="1">
{% autoescape off %}
{{table.rows|table_rows}}
{{table.cols|table_cols}}
{% endautoescape %}
</table>
{% endfor %}
# You can make changes according to your requirement

First row with two items second one and next with three

I have model (Event) and I want to have template with two ways to display items.
First row have to include two items, with special styling
Second one and next have to include three, with special styling
How can I do this with loop?
you can do like below
views.py
def view(request):
events = Event.objects.all()
l = []
for i in range(0,len(events), 5):
l.append((events[i:i+2], events[i+2:i+5]))
return render(request, "template.html", {"events": l})
template.html
{% for two_items, three_items in events %}
<tr class="class1">
{% for item in two_items %}
<td> {{ item }}</td>
{% endfor %}
<tr>
<tr class="class2">
{% for item in three_items %}
<td> {{ item }}</td>
{% endfor %}
<tr>
{% endfor %}
Combination of cycle and forloop tags will give you desired output:
For example:
{% for item in items %}
{% if forloop.counter < 3 %}
{% if forloop.first %}
<tr class="A">
{% endif %}
<td>{{ item }}</td>
{% endif %}
{% if forloop.counter == 3 %}
</tr>
{% endif %}
{% if forloop.counter >= 3 %}
{% cycle "<tr class='B'>" "" "" %}
<td>{{ item }}</td>
{% cycle "" "" "</tr>" %}
{% endif %}
{% endfor %}

Comparing appengine database values in Django

Hi i have an appengine application with the following db.Model:
class Cinema(db.Model):
name = db.StringProperty()
address = db.StringProperty()
distance = db.IntegerProperty()
user = db.ReferenceProperty(RunningUser)
When I fill my template everythings works fine:
{% for cinema in cinemas %}
<tr>
<td><img src="/images/cinema.png"></td>
<td>
<a href="...">
<h2>{{cinema.name}}</h2>
</a>
{{cinema.address}}
</td>
<td>
{% if cinema.distance > 10000 %}
<p>red</p>
{% endif %}
</td>
</tr>
{% endfor %}
Except the if statement. Python raises a TemplateSyntaxError: 'if' statement improperly formatted exception. According to Django it should be fine. So what is wrong with these three lines?
{% if cinema.distance > 10000 %}
<p>red</p>
{% endif %}
try this:
{% if cinema.distance > 10000 %}
<p>red</p>
{% endif %}
from: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#id3