【问题标题】:Django: Check if updated field is already present in databaseDjango:检查数据库中是否已经存在更新的字段
【发布时间】:2019-11-11 07:42:53
【问题描述】:

我正在尝试使用电子邮件作为字段来更新 django ModelForm。在创建表单中,我正在检查该字段是否已存在于数据库中,如果存在则引发验证错误。该部分按预期工作。

但是,如果我在更新表单中使用相同的检查,则会引发验证错误,因为现有记录具有给定的电子邮件。是否有直接的方法来确保此验证?

forms.py

class MyObjCreateForm(forms.ModelForm):
    first_name = forms.CharField(max_length=50, label='First name')
    last_name = forms.CharField(max_length=50, label='Last name')
    email = forms.EmailField(label='Email')
    location = forms.ChoiceField(choices=TP_TM_Location, label='Location')
    designation = forms.ChoiceField(choices=TP_TM_Designation, label='Designation')
    date_of_joining = forms.DateField(label='Date of joining',
                                    widget=forms.TextInput(attrs={'type': 'date'}),
                                    initial=date.today())
    username = forms.CharField(label='Login username')
    password = forms.CharField(widget=forms.PasswordInput(), label='Login password')
    current_status = forms.ChoiceField(choices=TP_Status, label='Current status')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            match = MyObj.objects.get(email=email)
            raise forms.ValidationError("email already exists in system. Please check the existing list.")
        except MyObj.DoesNotExist:
            return email

class MyObjUpdateForm(forms.ModelForm):
    first_name = forms.CharField(max_length=50, label='First name')
    last_name = forms.CharField(max_length=50, label='Last name')
    email = forms.EmailField(label='Email')
    location = forms.ChoiceField(choices=TP_TM_Location, label='Location')
    designation = forms.ChoiceField(choices=TP_TM_Designation, label='Designation')
    date_of_joining = forms.DateField(label='Date of joining',
                                    widget=forms.TextInput(attrs={'type': 'date'}),
                                    initial=date.today())
    current_status = forms.ChoiceField(choices=TP_Status, label='Current status')
    username = forms.CharField(label='Login username')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            match = MyObj.objects.get(email=email)
            raise forms.ValidationError("email already exists in system. Please check the existing list.")
        except MyObj.DoesNotExist:
            return email

谢谢,

【问题讨论】:

    标签: django validation django-forms


    【解决方案1】:

    为此,您需要像这样从查询集中排除当前用户。

        def clean_email(self):
            email = self.cleaned_data.get('email')
            email_match = MyObj.objects.filter(email=email).exclude(pk=self.instance.pk)  
            if self.instance and self.instance.pk and not email_match:
                return email
            else:
                raise forms.ValidationError("email already exists in system. Please check the existing list.")  
    

    【讨论】:

      【解决方案2】:

      您需要删除更新类中的验证。您可以直接退回电子邮件而无需验证。

      def clean_email(self):
          return self.cleaned_data.get('email')
      

      但是,如果您想检查用户是否已经拥有新的电子邮件,那么您可以使用以下验证方法:

      def clean_email(self):
          email = self.cleaned_data.get('email')
          if self.instance.email == email:
              raise forms.ValidationError("Email already present.")
          return email
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多