Reputation: 748
I have just begun using Django and I have the following scenario:
I have a model class Video
, the length of which I am calculating through a helper method and it is not an attribute (atleast currently).
So I am using a method in the Video class such that, we can call the method on an Video object like
length = video_obj.video_length()
to get the length in seconds
My question is while listing a group of videos on a page(I just iterate through the videos in the template and there is no Video object passed to the template), how do I display the length in minutes:seconds
format
I thought of the following -
Calling the video_length() function in the controller for that page and then pass the values as custom variable, but again that wont be video specific (I don't iterate through videos in the controller)
Last resort add it as an attribute
Please suggest the best way to implement this. Thanks in advance for your suggestions.
Upvotes: 0
Views: 62
Reputation: 47222
You could/should write a custom filter for this task since it's not the controllers responsibility to know how to format dates, it's the templates.
Then you could argue for the case of fat models, which I'm all for, but then again you might want to change formatting for another view and having a lot of different formatting methods will just bloat your class.
import datetime
def formatted_length(value):
"""
Formats the time in seconds to time in hours:minutes:seconds
"""
return str(datetime.timedelta(seconds=value))
And then you can use it like this in your templates
{{ video_obj.video_length|formatted_length }}
Upvotes: 1
Reputation: 338
You could add the @property
decorator above the method and in your templates you can access video.video_length
https://docs.python.org/2/library/functions.html#property
If it returns it as an integer of seconds then you could easily create a filter to convert it to minutes:seconds.
Upvotes: 1