0

How can I format a date in html from flask render_template? I am getting cabinet table from sqlalchemy where the date is formatted 2020-03-31 10:55:15.500207. I just need %Y-%m-%d.

 {% for item in cabinet %}
                <tr>
                    <td>{{item.name}}</td>
                    <td>{{item.stocktaking.strftime('%Y-%m-%d')}}</td>
                    <td>
                      {% if item.incomplete == true %}<span class="btn btn-sm btn-secondary">Incomplete</span>
                      {% else %}<span class="btn btn-sm btn-success">Complete</span>
                      {% endif %}
                    </td>
                    <td><a class="btn btn-sm btn-primary" href="{{ url_for('stocktaking_cabinet', name=item.name) }}" role="button">Show</a></td>
                    <td><a class="btn btn-sm btn-danger" href="{{ url_for('stocktaking_cabinet_reset', name=item.name) }}" role="button">Reset</a></td>
                  </tr>

Table:

class Cabinet(db.Model):
    id         = db.Column(db.Integer, primary_key=True)
    name       = db.Column(db.String(20))
    stocktaking = db.Column(db.DateTime, default=datetime.now())
    incomplete    = db.Column(db.Boolean)

strftime('%Y-%m-%d') is not working inside the html. It shows this error : jinja2.exceptions.UndefinedError: 'None' has no attribute 'strftime'

Patrick Yoder
  • 1,065
  • 4
  • 14
  • 19
Roman
  • 83
  • 1
  • 1
  • 10
  • can you show me your cabinet list ? – Abhishek Kulkarni Mar 31 '20 at 09:01
  • Look at this: https://stackoverflow.com/questions/4830535/how-do-i-format-a-date-in-jinja2 – shoytov Mar 31 '20 at 09:07
  • I try to use @app.template_filter('dt') def _jinja2_filter_datetime(date, fmt=None): if fmt: return date.strftime(fmt) else: return date.strftime(gettext('%%m/%%d/%%Y')) but same error jinja2.exceptions.UndefinedError: 'None' has no attribute 'strftime' – Roman Mar 31 '20 at 09:37

1 Answers1

1

Check your database directly. I think you'll find that stocktaking is null which translates to None in python.

You could change your template to use

<td>{% if item.stocktaking %}{{item.stocktaking.strftime('%Y-%m-%d')}}{% else %}None{% endif %}</td>

Also, you need to change this line to pass the function itself and not the result or you will find that your default date will be too old if your program runs continuously for more than a day.

stocktaking = db.Column(db.DateTime, default=datetime.now)
Dan Safee
  • 1,488
  • 1
  • 13
  • 18
  • table data stored is OK but look like this : 2020-03-31 10:55:15.500207 i want just 2020-03-31. i check @shoytov link and when i try make filter every time show error : jinja2.exceptions.UndefinedError: 'None' has no attribute 'strftime' – Roman Apr 01 '20 at 21:03
  • Show us the view function that is passing the `cabinet` data to the template. Maybe that will yield a clue. – Dan Safee Apr 02 '20 at 11:23
  • cabinet ​=​ Cabinet.query.all() – Roman Apr 07 '20 at 08:15