[Fixed]-ValidationError raises when updating

1๐Ÿ‘

โœ…

If your form is from the type ModelForm, you have an attribute self.instance. Then you can check if self.instance.id is set, and handle your validation.

if self.instance.id:
    # raise ValidationError

If you are not using it, should clean the id, which should be send with the request. Throw ValidationError if it exists, or continue..

id = self.cleaned_data.get('id', None)
if id:
     # raise ValidationError

Example:

def clean_examination(self):
    new_exa = self.cleaned_data.get('examination')
    try:
        old_exa = GeneralData.objects.get(
            examination=self.cleaned_data.get('examination'))
    except GeneralData.DoesNotExist:
        return new_exa

    if old_exa:
        if not self.instance.id:
            raise forms.ValidationError(
                'Object with this examination already exists!')
    return new_exa

In this situation, the ValidationError will only be raised if there is an old examination if there is no old object.

Note that IF the object has an id, changes to the name that already exists with an OTHER id, you will have two different objects with the same examination. Not sure if that is okay, but that is up to you of course.

๐Ÿ‘คNrzonline

Leave a comment