Search code examples
flaskflask-admin

I use Flask-Admin ModelView. I want to know which field in the model is changed when calling `after_model_change`


class View(ModelView):    
    def after_model_change(self, form, model, is_created):
        if model.is_enabled:
            subject = "subject"
            template = render_template('template.html')

            mail.send_email(from_email='example@mail.com',
                          to_email=model.email, subject=subject, text=template)

Solution

  • I found this solution. edit_form method instantiate model editing form, and I take the value I need. After that in after_model_change method, I check if this value is changed and decide whether to send the email.

    class View(ModelView):    
        def after_model_change(self, form, model, is_created):
            if self.user_is_enabled != model.is_enabled:
                if model.is_enabled:
                    subject = "subject"
                    template = render_template('template.html')
    
                    mail.send_email(from_email='example@mail.com',
                                  to_email=model.email, subject=subject, text=template)
    
        def edit_form(self, obj=None):
            try:
                self.user_is_enabled = obj.is_enabled
            except AttributeError:
                pass
    
            return ModelView.edit_form(self, obj)