pallets-eco / flask-admin

Simple and extensible administrative interface framework for Flask
https://flask-admin.readthedocs.io
BSD 3-Clause "New" or "Revised" License
5.79k stars 1.57k forks source link

How to suppor Timestamp #1567

Open Larryrun80 opened 6 years ago

Larryrun80 commented 6 years ago

Hi, flask-admin is very convenient to build a backend quickly, thanks for this great effort. Just write to ask if flask-admin can support timestamp easily? I have a MySQL DataTable, and use Integer type to store timestamp info. Now I tried to show it in backend and use a sqlalchemy column type DateTime or Timestamp in the model, it looks works in the list view, and seems also works when it set to column_editable_list (but I found the date picker widget can only support to year 2015). But when I try to set it as a form column, flask admin always says 'int' object has no attribute 'strftime'.

I'm a newbie to flask-admin and sqlalchemy, can you give me some advice? thanks.

ljluestc commented 4 months ago

# Custom model view for DataTable
class DataTableView(ModelView):
    column_list = ('id', 'timestamp_int', 'timestamp_datetime')
    column_editable_list = ('timestamp_int', 'timestamp_datetime')

    def on_form_prefill(self, form, id):
        if id:
            # Pre-fill form with existing data
            record = DataTable.query.filter_by(id=id).first()
            if record:
                form.timestamp_datetime.data = record.timestamp_datetime

    def on_model_change(self, form, model, is_created):
        # Convert integer timestamp to datetime object
        if form.timestamp_int.data:
            model.timestamp_datetime = datetime.utcfromtimestamp(form.timestamp_int.data)

    def on_form_change(self, form, model, is_created):
        # Convert datetime object to integer timestamp for form submission
        if form.timestamp_datetime.data:
            form.timestamp_int.data = int(form.timestamp_datetime.data.timestamp())

# Create Flask-Admin instance
admin = Admin(app, name='Flask Admin', template_mode='bootstrap3')
admin.add_view(DataTableView(DataTable, db.session))

if __name__ == '__main__':
    app.run(debug=True)