'IntegrityError in django duplicated key
Hello I have a form on django that im trying to validate so it does not allow duplicated values, as of right now when you enter a duplicated value it raises this error on the app:
Exception Type: IntegrityError
Exception Value:
duplicate key violates uniqueness restriction «utiles_employee_user_id_key»
DETAIL: The key already exists (user_id)=(3).
Here's my form:
class EmployeeForm(Form):
first_name = CharField(max_length=40, label=_('Nombre'))
last_name = CharField(max_length=40, label=_('Apellido'))
children = IntegerField(label=_('Cantidad de Hijos'), required=False)
email2 = EmailField(label=_('Correo electrónico personal'), required=False)
email = EmailField(label=_('Correo electrónico Corporativo'))
company = ModelChoiceField(queryset=Company.objects.all(), required=False, label=_('Empleado de'))
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
label_suffix=None, empty_permitted=False, user=None):
super().__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted)
if not user.is_staff:
self.fields['company'].queryset = Company.objects.filter(id=user.employee.company.id)
how can I raise an error message saying to the user that it entered a duplicated object, as of right now the app crashes when I do.
EDIT: I added this method to the form but the problem persist.
def clean(self):
cd = self.cleaned_data['email']
user = Employee.objects.get(email2=cd)
if self.instance and not user == self.instance:
raise ValidationError('trial msg')
return cd
but now i get this error:
Exception Type: AttributeError
Exception Value:
'EmployeeForm' object has no attribute 'instance'
Solution 1:[1]
You can achieve the desired behavior using the clean method. This method is present either on the Field definition itself and also on the Form.
You can find more detailed information on Django's documentation:
By raising a ValidationError when the duplicate data is present, it will allow you to detect the issue in the view and then display/render the desired error message.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dethos |
