Coder949
Coder949

Reputation: 1007

How and where to format date in Django (Python, Ajax)?

Can I format the date in the foreach loop ?

advertisements_list = []
    for advertisement in advertisements:
         advertisements_list.append({
            'id': advertisement.id, 
            'description': advertisement.description,
            'title': advertisement.title,
            'picture_url': advertisement.image.url,
            'date': advertisement.date -> format that })

In my template I would do something like {{ advertisement.date | date:"d.m.Y" }}. Is there something similiar which I can use in my foreach-loop ? I can not go the template way because it is Ajax.

Is it even the right place for formatting or should I do the formatting with JavaScript/jQuery when I passed the data ?

Upvotes: 1

Views: 314

Answers (2)

BuddhaGautama
BuddhaGautama

Reputation: 34

In addition to the first answer, what you can do is to add a method to the advertisement class which returns a properly formatted date (and there are a few ways to achieve that). Call it "formattedDate" for example. Then the code fragment you provided will become much cleaner.

Upvotes: 0

Astik Anand
Astik Anand

Reputation: 13047

You can do this way:

'date': advertisement.date.strftime('%y-%m-%d %H:%M:%S %Z')

Upvotes: 2

Related Questions