Hi,
I need to add some condition on the time base , right now the value of time i am getting from database is like 2012-09-05 05:05:05 and i need to add 24 hours in this.
I need to show different content on time base, like for original time i need to show "hi" and after 24 hours i need to show "hello" in the template file.
How can i do this? Please help me.
probably a custom template tag would be a nice way: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters . you could implement your own deltaDays tag with parameters, i.e. {{ date|deltaDays:1 }}.
You could also do this as a cheap filter.
from django import template
register = template.Library()
#register.filter()
def is_at_least_24_hours_ago(value):
import datetime
original_date_plus_24 = value + datetime.timedelta(hours=24)
right_now = datetime.datetime.now()
if right_now >= original_date_plus_24:
return True
return False
Then in your template:
{% if object_date|is_at_least_24_hours_ago %}
// It's 24 hours later
{% else %}
// It's not
{% endif %}
This is sample on how to add day(s),
import datetime
b = var_name + datetime.timedelta(0,3) # days, seconds
or
datetime.timedelta(days=1)
pass the value through view then use if statement in your template
Related
I'm trying to write a context processor core.context_processors.year.year that will pass a variable year to the template, the value of which will be the current year as a number: © {{ year }} Copyright
from datetime import datetime, date
def year(request):
return {
request, datetime.now().date()
}
You need to return a dictionary, not a set. That dictionary should contain as key the name of the variable, and as value the value you want to associate with that, so here this will look like:
from django.utils.timezone import now
def year(request):
return {
'year': now().year
}
You can use the Built-in "now" templatetag https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#now
© {% now "Y" %} Copyright
I figured out how to do it, initially I did it wrong. Thanks to everyone who responded.
from datetime import datetime
def year(request):
dt = datetime.now().year
return {
'year': dt
}
So I have a dictionary called match. This has details of a match and one of the keys are game_time. If the game time is <= 10, the match is in draft. Else, I want to report the game time but the value its stored in is just in seconds.
{% if match.game_time <= 10 %}
drafting
{% else %}
{{match.game_time|date: "Z"}}
{% endif %}
Just gives me an error
Could not parse the remainder: ': "Z"' from 'match.game_time|date: "Z"'
any help appreciated
Use this formate for time
{{your_date_field|time:"h:i a"}}
from datetime import datetime, timedelta
def millisec_to_time(millisec):
d = datetime(1, 1, 1)+millisec
if d.day - 1 == 0:
return "{0}:{1}:{2}".format(d.hour, d.minute, d.second)
else:
return "{0}:{1}:{2}:{3}".format(d.day-1, d.hour, d.minute, d.second)
Try this to convert sec/msec to actual time.
If you install mathfilters, add it to your install_apps, and load it into your template then you can do this.
{{ booking.duration|div:3600|floatformat:"2" }}
I'm using a Django custom template filter as described here to access entries in a 3D array in my template. I pass the 3D array swipeData from views.py to index.html.
index.html:
function getNearestHalfHourTimeString() {
var now = new Date();
var hour = now.getHours();
var minutes = now.getMinutes();
var ampm = "AM";
if (minutes < 15) {
minutes = "00";
} else if (minutes < 45){
minutes = "30";
} else {
minutes = "00";
++hour;
}
return("T" + hour + minutes);
}
var currentDay = (new Date()).getDay();
var currentTimeRounded = getNearestHalfHourTimeString();
{% block content %}
{% load hello_extras %}
var atrium = {{swipeData|bldIndex:'ATRIUMCAFE'|dayIndex:currentDay|timeIndex:currentTimeRounded }};
{% endblock %}
hello_extras.py:
from django import template
register = template.Library()
#register.filter
def bldIndex(List, strIndex):
dctBuild = {'ATRIUMCAFE':0, 'BUTLERCOLLEGE':1, 'CAFEVIVIAN':2, 'CENTERFORJEWISHLIFE':3, 'CHANCELLORGREEN':4, 'CHEMISTRYCAFE':5, 'CONCESSIONS_12':6, 'FORBESCOLLEGE':7, 'FRISTCSTORE':8, 'FRISTGALLERY1':9, 'FRISTGALLERY2':10, 'FRISTGALLERY3':11, 'FRISTGALLERY4':12, 'FRISTWITHERSPOONS':13, 'GRADUATECOLLEGE':14, 'LIBRARY_CART':15, 'MATHEYCOLLEGE':16, 'ROCKEFELLERCOLLEGE':17, 'STUDIO34BUTLEREMPORIUM':18, 'WHITMANCOLLEGE':19, 'WILSONCOLLEGE':20, 'WOODROWWILSONCAFE':21, 'FIRESTONELIBRARY':22}
i = int(dctBuild.get(strIndex))
return List[i]
#register.filter
def dayIndex(List, strIndex):
return List[int(strIndex)]
#register.filter
def timeIndex(List, strIndex):
dctTime = { "T0000":0, "T0030":1, "T0100":2, "T0130":3, "T0200":4, "T0230":5, "T0300":6, "T0330":7, "T0400":8, "T0430":9, "T0500":10, "T0530":11, "T0600":12, "T0630":13, "T0700":14, "T0730":15, "T0800":16, "T0830":17, "T0900":18, "T0930":19, "T1000":20, "T1030":21, "T1100":22, "T1130":23, "T1200":24, "T1230":25, "T1300":26, "T1330":27, "T1400":28, "T1430":29, "T1500":30, "T1530":31, "T1600":32, "T1630":33, "T1700":34, "T1730":35, "T1800":36, "T1830":37, "T1900":38, "T1930":39, "T2000":40, "T2030":41, "T2100":42, "T2130":43, "T2200":44, "T2230":45, "T2300":46, "T2330":47}
i = int(dctTime.get(strIndex))
return List[i]
I get the error
VariableDoesNotExist at /
Failed lookup for key [currentDay] in u"[{
How can I use a variable as an argument to my custom template filter? I've tried using a with block already.
Your problem is that you are trying to pass a JS var to a django filter, that it's wrong
currentDay and currentTimeRounded are JS Vars not Python vars, for this reason filter fails
Remember that you can get all necessary info in your view, and then render in your template
I suggest you that format your data in your view and in the template assign it to the respective JS var
some as follow
def some_view(request):
# here you can calculate, convert, create all values to your chart as you need
# if you need time or date can use datetime module ie
values_to_chart = ""
render(request, template_name, locals())
And in your template
var atrium = {{values_to_chart}}
I have in my jinja2 template code for localization.
{% set currency = "SEK" %}
{% set format = "sv_SE" %}
{% set timezoneinfo = 'Europe/Stockholm' %}
{% set locale = "se" %}
But it's not working for hours and minutes if I use it like this with a filter using values from a google search API result to filter.
{{scored_document.fields.10.value|datetimeformat_list(hour=scored_document.fields.17.value|int ,minute =scored_document.fields.18.value|int, timezoneinfo=timezoneinfo, locale=locale)}}
filter
def datetimeformat_list(date, hour, minute, locale='en', timezoneinfo='Asia/Calcutta'):
tzinfo = timezone(timezoneinfo)
input = datetime(date.year, date.month, date.day, int(hour), int(minute), tzinfo=tzinfo)
time_str = format_time(input, 'H:mm', tzinfo=tzinfo, locale=locale)
return "{0}".format(time_str)
The code gives a different time than if I just do
{{ ad.modified|datetimeformat_viewad(locale='se', timezoneinfo='Europe/Stockholm') }}
with this filter
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='Asia/Calcutta'):
tzinfo = timezone(timezoneinfo)
month = MONTHS[to_format.month - 1]
date_str = '{0} {1}'.format(to_format.day, _(month))
time_str = format_time(to_format, 'H:mm', tzinfo=tzinfo, locale=locale)
return "{0} {1}".format(date_str, time_str)
Why are the outputs not the same time?
It is incorrect to pass an arbitrary pytz timezone to datetime constructor directly; you should use pytz_tzinfo.localize() method instead as it is said at the very beginning of pytz docs.
There could be other issues in your code.
I have a django application, a blog. The entries for the blog can be accessed through a /year/month/day/slug url pattern, it works fine.
My problem is, I want to have an archive list accessible to any template on my website. So i thought the best solution would be to create a templatetag that would create and return the info i needed.
I wanted the format of the archive to be as such:
August 2011
July 2011
etc..
2010
2009
2008
etc..
So only show months for the current year.
This is the tag i came up with:
from django.template import Library, Node, TemplateSyntaxError
from core.blog.models import Entry
import datetime, calendar
register = Library()
class ArchiveNode(Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
temp = list()
#Get Info about the first post
first = Entry.objects.order_by("pub_date")[0]
first_year = first.pub_date.year
first_month = first.pub_date.month
#Loop over years and months since first post was created
today = datetime.datetime.today()
this_year = today.year
this_month = today.month
for year in range(this_year - first_year):
if year != this_year:
temp += (year,'/blog/'+year+'/')
else:
for month in range(this_month - first_month):
month_name = calendar.month_name[month]
temp += (month_name+" "+year,'/blog/'+year+'/'+month+'/')
context[self.varname] = temp.reverse()
return ''
#register.tag
def get_archive(parser, token):
bits = token.contents.split()
if len(bits) != 3:
raise TemplateSyntaxError, "get_archive tag takes exactly 1 argument"
if bits[1] != 'as':
raise TemplateSyntaxError, "second argument to get_archive tag must be 'as'"
return ArchiveNode(bits[2])
As you can see im returning a list of tuples, containing a name and a url.
Would this be valid in django? or do i need to pack the information in some django container? (It's doen't seem to return anything)
This is the site im working on ctrl-dev.com/blog.
The archive will be in the green box on the lower right.
There is no need to return something special. Django is just Python, so it is your choice what you want to return. In this case I would recommend to return dictionary like this (just inventing) {{'title':'some title if you want','year': 'year if you want', 'url': url}, {...}, ...}. Then in template you just run through like:
{% for entry in returned_dict %}
{{ entry.title }}
{% endfor %}
Also I would recommend to not hardcode the link in to the code. Read https://docs.djangoproject.com/en/dev/topics/http/urls/ about url resolvers, then https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#url about {% url %} template tag. You can name the urls and later you can get the urls to the stuff you want without hardcoding it in the code. This will help in future ;)
Hope that helped.