Jisson
Jisson

Reputation: 3725

best way to pass processed values along with the object to a django template

I have a field timestamp in my table,which is of type long I want to dispaly it in the form of Django datetime (well I convert timestamp to datetime format), and some other atributes of the same object ,am using sqlalchemy2.7 and django1.3.

views.py

result = session.query(Member).order_by(desc(Member.timestamp))
   for instance in session.query(Member).order_by(desc(Member.timestamp)):
        time = instance.timestamp/1000     # 1314788935874
        print datetime.fromtimestamp(time) # 2011-08-31 06:08:55
    return render_to_response('Member/MemberData.html',{'result': result},context_instance=RequestContext(request))

MemberData.html

{% for instance in result %}
<li>

    {{instance.timestamp}} ::  {{instance.name}} ::  {{instance.age}}

</li>

{% endfor %}

now the outpt like :

1314788935874 :: James :: 21
1314788935874 :: John  :: 20
............................
............................

I need the output like :

  2011-08-31 08:32:16 :: James ::21
  2011-08-31 06:08:55 :: John :: 20
 ............................
 ............................ 

Thats I want to pass the 'time' varible to template, how can I pass it with minimum effort
Note: I want to pass converted timestamp and some other attributes of the object with out any change. Please suggest some standered ways,Thanks in advance.

Upvotes: 0

Views: 130

Answers (1)

kosmos342
kosmos342

Reputation: 852

Create your own template filter:

@register.filter
def from_timestamp(value):
    return datetime.fromtimestamp(value/1000)

and in templates: {{ instance.timestamp|from_timestamp|date:"Y-m-d H:i:s" }}

OR

views.py:

result = session.query(Member).order_by(desc(Member.timestamp))
for instance in result:
    time = instance.timestamp/1000
    instance.datetimestamp = datetime.fromtimestamp(time)
    return render_to_response('Member/MemberData.html',{
        'result': result}, context_instance=RequestContext(request))

and in templates: {{ instance.datetimestame|date:"Y-m-d H:i:s" }}

Upvotes: 4

Related Questions