Aakash Jain
Aakash Jain

Reputation: 760

Django: Check if updated field is already present in database

I am trying to update a django ModelForm with email as a field. In the create form, I am checking if the field is already present in database, if so raise validation error. That part is working as expected.

however, if I use the same check in update form, it throws validation error as the existing record has the given email. Is there a direct method to ensure this validation?

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

Thanks,

Upvotes: 1

Views: 784

Answers (2)

Arsh Doda
Arsh Doda

Reputation: 334

You need to remove the validation in update class. You can simply return the email without validation.

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

However, if you want to check if the user already has the new email,then you can use following validation method:

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

Upvotes: 0

Arjun Shahi
Arjun Shahi

Reputation: 7330

For this you need to exclude the current user from the queryset like this .

    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.")  

Upvotes: 2

Related Questions