I have the Django project with the Model to save date_added information. Here's the Model code.
class Outputting(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
And I want to retrieve such date_added information and demonstrate it as the local time in the html. How could I make the transformation? Here's the view.py and html template, but it still show the UTC time.
view.py
def results(request):
user = request.user
data = Outputting.objects.filter(owner=user).order_by('id').values_list('id','date_added')
return render(request, "xx.html", {"data": data})
Html:
<tr>
{% for i in data %}
<td style="word-wrap:break-word;"><div class="panel-body" type="datetime-local"><small>{{ i.1|date:'M d Y H:i:s' }}</small></div></td>
</tr class="something">
{% endfor %}
In your settings.py change the time zone location
TIME_ZONE = 'Africa/Abidjan'
if you don't know your location you can list all available time_zone options by running below command in the Django shell:
In [40]: import pytz
In [41]: pytz.all_timezones
Out[42]:
['Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
...]
Reference: https://stackoverflow.com/a/13867319/7470786
EDIT:
For this, you should dynamically get the location of the user. After searching I came across with this answer which suggest using getTimeZoneOffset.
You have to enable USE_TZ = True in your settings.py if you not.
In order to have value in localtime in the template you can do:
{% load tz %}
{% localtime on %}
{{ value }}
{% endlocaltime %}
Also you can set specific timezone like:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ value }}
{% endtimezone %}
Or if you need one value to be converted you can do:
{% load tz %}
{{ value|localtime }}
You can read more in Django official docs.
If you want to store it in UTC and display it in the local time, then do this
{% load tz %}
{% timezone "Asia/Kolkata" %}
India time: {{ value }} #Add your respective time
{% endtimezone %}
{% timezone None %}
Server time: {{ value }}
{% endtimezone %}
This will return UTC if no time zone is given.
Note that - Conversion to local time is not always appropriate.
Also check out the warning inside Official Docs
Related
In my Jinja template, model.DataType value can be user defined or built in. My requirenement is if model.DataType start with the three letters ARR, then do a specific operation.
Example of values:
ARRstruct124
ARR_int123
ARR123123
CCHAR
UUINT
etc.
{% set evenDataType = model.eventDataType %}
{%if evenDataType | regex_match('^ARR', ignorecase=False) %}
// do the operation
{%else%}
// do the operation
{% endif %}
With this template, I am getting the error
{%if evenDataType | regex_match('^ARR', ignorecase=False) %}
jinja2.exceptions.TemplateAssertionError: no filter named 'regex_match'
There is indeed no regex_match filter in the Jinja builtin filters. You might have found some examples using it, but this is an additional filter provided by Ansible, so it won't work outside of Ansible.
This said, your requirement does not need a regex to be fulfilled, you can use the startswith() method of a Python string.
So, you template should be:
{% set evenDataType = model.eventDataType %}
{% if evenDataType.startswith('ARR') %}
`evenDataType` starts with 'ARR'
{% else %}
`evenDataType` does not starts with 'ARR'
{% endif %}
I need to display the information if the date given is in the future. Is there a way to do this in a template?
I found out I should compare them as timestamps but the following code gives me "jinja2.exceptions.UndefinedError: 'as_timestamp' is undefined".
{% if as_timestamp(bibjson.discontinued_date) <= as_timestamp(time.today) %}
<p>This date should be displayed only if in the past: {{ date.strftime("%d %B %Y") }}</p>
{% endif %}
It is very easy with custom filter https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/
The filter file:
import datetime
from django.template import Library
register = Library()
#register.filter('date_in_the_past')
def date_in_the_past(date):
now = datetime.datetime.now()
return date <= now
and in the template:
{% load filter %}
{% if bibjson.discontinued_date|date_in_the_past %}
<p>This date should be displayed only if in the past: {{ bibjson.discontinued_date|date:'d F Y' }}</p>
{% endif %}
I have an object in python views.py that references the events database table. When there is data, it displays the data in my html template, however, when there is no data, I cannot figure out the {% if %} function that would display the message "No data found."
I have tried Tadeck's post, but the is defined always seems to evaluate to true even if there is no data to display. Thank you for your help.
{% if events is defined %}
value of variable: {{ events }}
{% else %}
variable is not defined
{% endif %}
views.py
events = db.session.query(Eventdetails, Buyers).\
join(Buyers).\
filter(Eventdetails.events_id == event_id)
return render_template(
self.template_file, events=events, the_event=the_event,
event_id=event_id
)
You are passing events as the query. You want it to be the query results:
events = db.session.query(Eventdetails, Buyers).\
join(Buyers).\
filter(Eventdetails.events_id == event_id).all()
Things to try:
{% if events %}
{% if events|length > 0 %}
{% if events != [] %}
This will help you. When event have data then it will go inside the if condition otherwise else will be execute No data found.
{% if events %}
value of variable: {{ events }}
{% else %}
No data found.
{% endif %}
I have a state using file.managed, which generates a config file via a jinja for loop from a key in pillar.
My pillar looks like this:
configuration:
server01:
key1: value1
key2: value2
server02:
key03: value03
key04: value04
and the managed file:
{% set kv = pillar['configuration']['server01'] %}
{% for key, value in kv.iteritems() %}
{{ key }}:{ value }};
{% endfor %}
The way I differentiate between different servers right now in my state file is
config:
file.managed:
- name: /etc/config.conf
- source: salt://files/{{ grains['id'] }}.conf.jinja
- template: jinja
but this is less than ideal, since I have to create an almost identical file for every server.
Is there a way to dynamically replace server01 with the ID of the actual server, something like
{% set kv = pillar['configuration']['{{ grains[id''] }}'] %}
The goal is to generally limit the necessary changes only to the corresponding pillar file, when adding a new server, so other suggestions are also welcome too.
i think you should use pillar info in your state file.
your state file like bellow :
{% if grains['id'] in pillar['configuration'] %}
{% set nodeinfo = pillar['configuration'][grains['id']] %}
config:
file.managed:
- name: /etc/config.conf
- source: salt://conf.jinja
- template: jinja
- defaults :
nodeinfo: {{nodeinfo}}
{% endif %}
then, conf.jinja:
{% for key, value in nodeinfo.iteritems() -%}
{{ key }}:{{ value }};
{% endfor -%}
i hope that will solve your problem, thanks.
I am trying to get Django user's group in HTML for an if tag. This is what I tried:
{% ifequal user.groups.all.0 'ABC' %}
{% endif %}
But this is not working. What other way is there?
Try this:
{% for group in request.user.groups.all %}
{% if group.name == 'ABC' %}{% endif %}
{% endfor %}
Or
{% if request.user.groups.all.0.name == 'ABC' %}{% endif %}
You have to access the current user object from the request context variable. For this, make sure that django.template.context_processors.request is in your template settings.
request.user.groups.all.0 returns a Group model object, so you have to compare against the name field.
I think you will have to use a little Python here. For example, a custom template tag:
#register.filter(name='has_group')
def has_group(user, group_name):
return user.groups.filter(name=group_name).exists()
And in your template:
{% if request.user|has_group:"ABC" %}
...
{% endif %}
(Source: http://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/)
But maybe you should actually use permissions here.
https://docs.djangoproject.com/en/1.8/topics/auth/default/#authentication-data-in-templates
Edit: Here is a more complete example of the custom template tag:
settings.py:
INSTALLED_APPS = [
...
'yourapp',
...
]
Filesystem:
yourproject/
manage.py
yourproject/
settings.py
wsgi.py
...
yourapp/
__init__.py
templatetags/
__init__.py
yourapp_extras.py
...
yourapp_extras.py:
from django import template
register = template.Library()
#register.filter(name='has_group')
def has_group(user, group_name):
return user.groups.filter(name=group_name).exists()
Template:
{% load yourapp_extras %}
{% if request.user|has_group:"ABC" %}
...
{% endif %}
To get a more thorough understanding of this, I highly recommend reading Django's excellent documentation.
<h1>{{ user.groups.all.0 }}</h1>
{% if user.groups.all.0.name == 'Team2' %}
<h1>YES</h1>
{% else %}
<h1>NO</h1>
{% endif %}
Here, the user.groups.all.0 gives you the first group assigned to the user.
For eg. if the logged in user has groups assigned to him as- 'Team2', 'Programmer', 'Beginner'.
Then {{user.groups.all.0}} will print Team2.
I've used it to print and check the logged in user's group in html template.
OR
{% if request.user|has_group:"mygroup" %}
<h1>Has group mygroup</h1>
{% endif %}
Also works fine in django v1.11. This will check if the current user has 'mygroup' assigned to it or not.
However you'll need to add
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 True if group in user.groups.all() else False
inside a group_check.py in below file structure
--app
|templates
|templatetags
|-- group_check.py