Finer control over Django timeuntil output possible? - python

I'm currently using the timeuntil tag to show an items expiration date. It's currently spitting out...
{{rental_till|timeuntill}}
Which produces...
3 months, 1 week
Is it possible to get it to just show, the months, for example? Or any type of finer control over the output format, similar to the date tags.

To only show months, you could write a simple template filter that splits the string on the comma, and returns the first item of the resulting list. The filter code would look like this:
from django.template import Library
register = Library()
#register.filter
def split_timeuntil(duration):
return duration.split(",")[0]
Then in your template: {{rental_till|timeuntil|split_timeuntil}}
However, the timeuntil filter does not have the kind of formatting date has. You can easily create a custom filter that returns the format you want by copying the timeutil code in django/template/defaultfilters.py and django/utils/timesince.py.

No, timeuntil doesn't have any options, but you can simply create your own templatetag based on timeuntil and make it do whatever you like. See: https://code.djangoproject.com/browser/django/tags/releases/1.3/django/template/defaultfilters.py (line 729)

Related

Permanently replace value in Django

After extensive googling, I still havent come up with an effecient way to solve this.
Im creating a website using Django. I have a db which contains time data, more specifically dates. The value for "the present" is set to 3000-01-01 (YYYY-MM-DD) as is common practice for time-querying.
What I want to do is display a string like "Now" or "Present" or any other value instead of the date 3000-01-01. Is there some sort of global override anywhere that I can use? Seems like a waste to hard-code it in every view/template.
Cheers!
Since this is rendering, I would advice against "subclassing" the DateField such that it renders 'now' instead of the original date(..) object: it will make calculations in the model layer more cumbersome.
Probably a good way to deal with this is implementing a template filter [Django-doc], for example we can construct a file:
# app/templatetags/nowdate.py
from django import template
register = template.Library()
PRESENT = date(3000, 1, 1)
#register.filter
def nowdate(value):
if value == PRESENT:
return 'present'
return value
The templatetags directory of the app application, needs to contain an __init__.py file as well (an empty file), and the app of course needs to be part of the INSTALLED_APPS in the settings.py.
Then we can use it in the template like:
<!-- app/templates/app/some_template.html -->
{{ some_model.some_date_field|nowdate }}
Here we thus fetch the some_date_field of the some_model variable (this attribute is thus a date(..) object), and we pass it through the nowdate filter we have constructed such that, if it is 3000-01-01, it is replaced by the 'present' string.
The advantage here is that if we later change our mind about what date the "present" is, we can easily change it in the template filter, furthermore we can easily extend it, for example by adding a 'past', 'future', etc.

Creating a date filter in jinja2

I'm trying to work out the age of a record in my jinja2 with a filter. I created a simple filter in the following way. The date is stored in a mongodb field and its original form should be of the format of the python datetime object. Here is an example of the record:
"date_update": {
"$date": "2016-02-29T11:13:41.730Z"
},
app.jinja_env.filters['record'] = lambda u: record(u)
def record(date_obj):
print(date_obj)
print(type(date_obj))
return (datetime.datetime.today() - date_obj).days
I use the filter in the following way:
{{ myrec.date_update|record }}
If I look at the output, I see the following:
class 'jinja2.runtime.Undefined'
So my question is, how best should I deal with the dates in jinja2 in the correct format.
This looks like an unknown variable name within your template. From all you've posted so far, it is not clear whether you pass a variable myrec to the template renderer in the first place. So for better help, please post a minimal, self-contained example that exhibits the error.

Parametrizing a Date on urls.py in Django

I have the following URL definition:
url(r'^date-add/(?P<entity_id>\d+)$', views.date_add, name='date_add'),
That allows me to call date_add function with the following URL:
/app_name/date-add/<id>
I would like to fix this to allow a date. For example:
/app_name/date-add/1/2013-04-23
How should I edit my urls.py definition in order to achieve this?
You can define your URL regex like this:
url(r'^date-add/(?P<entity_id>\d+)/(?P<date>\d{4}-\d{2}-\d{2})/$', views.date_add, name='date_add'),
and the view, obviously would be
def date_add(request, entity_id, date):
#convert to datetime object from string here.
Typically you break it down into named parameters corresponding to the year, month and date:
url(r'^date-add/(?P<entity_id>\d+)/(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})/$', views.date_add, name='date_add_with_param'),
Then you can use datetime.date to construct the datetime in your view, which should receive year, month and day as parameters.
This is the usual pattern in particular for archive views, where the URLs might get more specific as you drill down - /archive/2013/ and /archive/2013/11/ might both be valid, although of course you probably wouldn't have a single regexp matching either. It might be unnecessarily complex compared to the single named pattern regexp karthikr's answer shows, which you could then parse with datetime.strptime.
In either case you can also use somewhat more restrictive regexps if you like, like ones that don't allow a first digit other than 0, 1, 2 or 3 for the month.

How to index one field Dates with a list of dates in Plone

I want to create an event content type with one field Dates contains a list of dates (not recurring dates) and displayed in Plone like the official event content type.
I want to have one event that display many times in the portlet Calendar.
Is this possible and how (which addon to use, ...)
I'm currently trying MultiEvent addon (I have updated from Plone2.5 -> Plone4.1) but this addon need a cron to call an update method that change THE date to the next one. So you can't see the event more than one time in the calendar.
It seems DateIndex can manage one date for one content. I'm looking for a Keyword Index but for dates.
You could make your Event content a folderish, and insert date intervals inside it (as another content type).
Retrieving them with catalog would look like:
catalog = getToolByName(context, 'portal_catalog')
catalog( object_provides=IMyDateInterval.__identifier__,
sort_on='interval',
interval={ 'query' : date_range, 'range' :'min:max'}
)
Hope it helps.
Would the DateRecurringIndex work for you?
http://pypi.python.org/pypi/Products.DateRecurringIndex

django autoconverting datetime property

my datetime property is saving in mysql in this format 2011-03-17 00:00:00 but after fetchind the data with filter function it is giving March 17,2011 midnight but i have not say to do any this type of task. My question is how can i insist django to stic to show same value what is saved in MYSQL.
you'll want to use the datetime format, django's DateTimeField[1] really is a wrapper for datetime.datetime.
in the templates you can use the date[2] filter to apply the format you want for example:
{{ item.date|date:"Y-m-d H:i:s" }}
This should print out 2011-03-17 00:00:00 in the template. In views use datetimes.strftime[3]
[1] http://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield
[2] http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#date
[3] http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
I have a feeling your database schema knows this is a date, right? In that case it's not being stored in the format you describe, but as some representation such as seconds since the era.
This means that when you retreave it your code has to do something with it to make it look right. If you don't tell it how to look it'll default to the format you see, but if you use strftime in your python code and a filter in your templates you can make it look however you like, including the original format how you saw it.
Of course the easy way out is to store it in the db as text...

Categories

Resources