簡體   English   中英

IntegrityError in django 重復鍵

[英]IntegrityError in django duplicated key

您好,我在 django 上有一個表單,我正在嘗試驗證它,因此它不允許重復值,截至目前,當您輸入重復值時,它會在應用程序上引發此錯誤:

Exception Type: IntegrityError
Exception Value:    
duplicate key violates uniqueness restriction «utiles_employee_user_id_key»
DETAIL:  The key already exists (user_id)=(3).

這是我的表格:

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)

我怎么能發出一條錯誤消息,告訴用戶它輸入了重復的 object,截至目前,當我這樣做時應用程序崩潰了。

編輯:我將此方法添加到表單中,但問題仍然存在。

    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
            

但現在我得到這個錯誤:

Exception Type: AttributeError
Exception Value:    
'EmployeeForm' object has no attribute 'instance'

您可以使用clean方法實現所需的行為。 此方法存在於Field定義本身以及Form中。

您可以在 Django 的文檔中找到更詳細的信息:

通過在存在重復數據時引發ValidationError ,它將允許您檢測視圖中的問題,然后顯示/呈現所需的錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM