[Fixed]-Django Form output/Error Checking issue

1👍

You may be editing an existing object, right?
I would simply exclude it from the result set:

def clean_number(self):
    """Ensures the new  Number is unique """
    enteredNumber = int(self.cleaned_data['number'], 8)

    queryset = Number.objects.filter(number=enteredNumber)
    if self.instance is not None and self.instance.pk is not None:
        queryset = queryset.exclude(pk=self.instance.pk)

    if queryset.exists():
        raise forms.ValidationError("Error")
    return enteredNumber

Using the .exists() method avoids loading the object from the database, should one exist.

By the way, this form won’t ensure you cannot create duplicates. Two threads may run the validation code at the same time, accept the same value, then proceed to saving their respective object with that value.
If you want to be sure you don’t have duplicates, you must do so at the database level (by passing unique=True to the field on the model).

Leave a comment