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?