Home > Enterprise >  Use Form.has_changed() validation with Django UpdateView
Use Form.has_changed() validation with Django UpdateView

Time:04-27

I am trying to post a message when one or more of the values have changed in an UpdateView. Is this possible to do with Form.has_changed() with this generic view? For example:

class MyUpdateView(UpdateView):
    model = MyModel
    form = MyModelForm
    fields = "__all__"
    template_name = "mymodel_form.html"

    if form.has_changed():
        logger.info("Some values have changed")

CodePudding user response:

You can override the .form_valid(…) method [Django-doc] for this:

class MyUpdateView(UpdateView):
    model = MyModel
    form_class = MyModelForm
    fields = '__all__'
    template_name = 'mymodel_form.html'

    def form_valid(self, form):
        if form.has_changed():
            logger.info('Some values have changed')
        return super().form_valid(form)

or if you want to log changes if the form might be invalid as well, you can use .get_form(…) [Django-doc]:

class MyUpdateView(UpdateView):
    model = MyModel
    form_class = MyModelForm
    fields = '__all__'
    template_name = 'mymodel_form.html'

    def get_form(self, form_class=None):
        form = super().get_form(form_class=form_class)
        if form.has_changed():
            logger.info('Some values have changed')
        return form
  • Related