Skip to content
Advertisement

How to fix Django Duplicate key form from being valid and saved?

This is my views.py file and Im getting this message

JavaScript

However is see that Valid is printing so its obvious the is_valid() method doesnt catch this duplicate key.

JavaScript

EDIT Batting model and form

JavaScript
JavaScript

How is it I catch this issue?

Advertisement

Answer

In your form you have set exclude as follows: exclude = ('match',). When we exclude a field from the form, the form also excludes it from the validation it performs, which is only logical in the case that the form may be used to create this model’s instances.

Since you need the field match to be part of the validation the best method is to simply make match a disabled and hidden field on the form. This will cause the field to be rendered with the disabled and hidden attributes. Also even if the user tampers with the field it will be ignored in favor of the initial value of the field:

JavaScript
Advertisement