Home > other >  Flask-Admin: How to get the object being edited in validate_form
Flask-Admin: How to get the object being edited in validate_form

Time:08-04

I am trying to implement custom validation in the edit form. However, I don't know how to obtain the object that is being edited in the method validate_form.

class ShiftModelView(ModelView):
    """ModelView to manage Shift model."""

    def validate_form(self, form) -> bool:
        """Validate form."""
        if not super().validate_form(form):
            return False

        if form.scheduled_from.data >= form.scheduled_to.data:
            message = (
                "'Scheduled From' cannot be greater than or equal to 'Scheduled To'"
            )
            flash(message, "error")
            return False
        # HERE I NEED THE OBJECT THAT IS BEING EDITED

How can I achieve this?

CodePudding user response:

Add a hidden field to your wtform class to hold the object id, you can use this to load the object from your validate_form method. Add this field to your wtform class:

object_id = HiddenField("Object ID")

In your route where you populate your form, set the object_id:

ShiftForm.object_id = id

Add it to your jinja template:

{{ form.object_id }}

Then in the validate_form you should be able to access it with form.object_id.data and use the ID to pull the rest of the object out of the database.

The wiring might be slightly off due to different variable names but the first answer on this question has a working minimal example of using a wtform's hidden field, follow that and you should be good.

CodePudding user response:

The form has a protected member _obj that is the current object being edited.

def validate_form(self, form) -> bool:
    """Validate form."""
    if not super().validate_form(form):
        return False

    if form.scheduled_from.data >= form.scheduled_to.data:
        message = (
            "'Scheduled From' cannot be greater than or equal to 'Scheduled To'"
        )
        flash(message, "error")
        return False

    # HERE I NEED THE OBJECT THAT IS BEING EDITED
    
    print(form._obj)
  • Related