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

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

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

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

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

Any help please?


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
    qs = qs.exclude(

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.


Thank you very much. And that solved my issue.

Really grateful