Roman
Roman

Reputation: 83

Date formatting in Flask Html/jinja2?

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'

Upvotes: 0

Views: 1588

Answers (1)

Dan Safee
Dan Safee

Reputation: 1618

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)

Upvotes: 1

Related Questions