Search code examples
djangodjango-generic-viewsdjango-validation

How to correctly Validate user entry in Django Generic Views


In my Django app I am trying to validate a form field value entered by the user. I am trying to do the validation in Django generic UpdateView (as I will explain below). The extant field stores various statuses of a transaction document. The change in status happens at update (either by the user manually entering the status code OR based upon certain phase of transaction or the like - not important here).

The important thing is that on save the status of the document needs to change. As there are a number of statuses, each of them have been given a numerical value. Wherever the statuses are manually entered, the need is to check if the current status value is less than the entered value. If it is not, the user should get an error message.

My views.py looks like this:

class ProdDocView(UpdateView, ...):
    template_name = ...
    model = ProdLine
    form_class = ProdLineForm
    ...

    def form_valid(self, form):
        tmp_status = ProdLine.objects.get(prod_doc_id=self.object.pk).prod_doc_status
        new_status_entered = form.cleaned_data['prod_doc_status']

        if tmp_status == new_status_entered:    # This is just to check error capture
            # raise ValidationError('Wrong status code entered!!')
            return super(ProdDocView, self).form_invalid(form)
        else:
            form.instance.approved_by = self.request.user.   # This is to save user field on successful save
        return super().form_valid(form)

Now what is happening is, the error trapping happens - i.e. if the the previous status matches the status entered, saving fails. But no error message is displayed. If the statuses are unequal, the document successfully saves.

As you can see, the raise ValidationError('Wrong status code entered!!') code line has been commented out, because otherwise the form fails and the error is displayed in the browser (with the error message).

My question is:

How can I display the error to the front end user?


Solution

  • In order to close the question, I am reproducing my comment above:

    I just needed to add the following:

    form.add_error('prod_doc_status', 'Wrong status code entered!!')

    With this, the error message shows up against the field.