Validation preventing update

Hi everyone, I am currently learning Django and am stuck on updating a record.

I have a form from my model, and I also have a custom validation where I check if the record already exists before creating, which actually works fine on creation.

The problem then is when I want to update the record. In case I choose to edit the record but did not change the record and submit, it prevents the submission because the record already exists.

Below is the code

Validation:
city = City.objects.filter(city_name__iexact=city_name, status=True).exists()
print("City exists => ")
print(city)
if city:
raise ValidationError(_(“City already exist”))

View:
region = request.GET[‘region’]
city = City.objects.get(ref=ref)

if request.method == "POST":
    form = CityForm(request.POST, instance=city)
    print(form.data['city_name'])
    if form.is_valid():
        form.save()
        messages.add_message(request, messages.SUCCESS, 'City updated successfully')
        return redirect('/cities/?region=' + region)
else:
    form = CityForm(instance=city)

context = {
    'ref': region,
    'form': form,
}
return render(request, 'city/edit.html', context)

Any help please?

@clemsedem,

If it is a ModelForm, an option could be checking the instance to understand the context (if it’s creation or update) and if it’s an update process, use the pk to ensure you are not using the same name for other record.

I’m terrible explaining. It could be something like this:

qs = City.objects.filter(city_name__iexact=city_name, status=True)

if self.instance:  # not sure if it should be self.instance.pk
    qs = qs.exclude(pk=self.instance.pk)

if qs.exists():
    raise ValidationError(...)

If you have an instance City(pk=1, name=portland), and you save it without changes, the qs.exists() will return False. But if you try to create a new portland, or if you try to change other instance to portland, qs.exists() will return True.

I hope it helps.

1 Like

Thank you very much. And that solved my issue.

Really grateful