Gnanavel
Gnanavel

Reputation: 665

While updating records in django check whether the newly entered data is already matching with the other records in database?

forms.py

class RoleForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        if Group.objects.filter(name__iexact=name).exists():
            raise forms.ValidationError("Role name already exists")
        return name

views.py

def updateroles(request, id):
    roles = Group.objects.all()
    instance = get_object_or_404(Group, pk=id)
    if request.method == "POST":
        fm = RoleForm(request.POST, instance = instance)
        if fm.is_valid():
            fm.save()
            messages.success(request, 'Updated Successfully')
            return redirect('roles')
    else:
        fm = RoleForm(instance=instance)
    return render(request, 'crm/roles.html', {'form': fm, 'roles': roles})

While adding new records I want to check whether the records already exists in database.If it exist I need to raise a ValidationError which is working fine.But while updating records check whether the newly entered data is not matching with any other records,if it matches I need to raise a ValidationError like newly entered data matches with some other record.My current code is raising a validationerror even if I click on update without changing the existing data.Any help would be appreciated.

Upvotes: 1

Views: 251

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

You should exclude the object:

class RoleForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        # exclude the current instance ↓
        if Group.objects.exclude(pk=self.instance.pk).filter(name__iexact=name).exists():
            raise forms.ValidationError("Role name already exists")
        return name

Upvotes: 1

Related Questions