[Answer]-Django form validation looks like bad code

1👍

You’re using the wrong Queryset method here. get() returns a model object, which doesn’t in turn have an exists() method. You should use filter().

Also, exists() doesn’t raise an exception. So you can just do a normal if:

if Province.objects.filter(name=data).exists():
    raise forms.ValidationError(...)

Bear in mind as well that the clean method will be called for an update as well as a create. On an update, the check will fail because it will find the very same instance you’re editing. You should bypass this check if the form has an instance and the instance has a pk value:

if not (form.instance and form.instance.pk):

Finally, you should never use a bare except statement. That will catch all exceptions, potentially hiding some real problems with your code. Always catch the specific exception you think your code will raise – in this case, Province.DoesNotExist.

0👍

This won’t work since you’ll always handle the exception in your clean_name function and never raise the validation exception!

Instead do this


if Province.objects.filter(name=data).exists() or Region.objects.filter(name=date).exists():
  raise forms.ValidationError("...")

Beyond that, your code is just fine !

Leave a comment