'Django admin: Editing records with unique fields fails
Python 3.9, Django 3.2, Database is PostgreSQL hosted on ElephantSQL.
I have a model with a slug field which I have set to unique:
class website_category(models.Model):
fld1 = models.CharField(primary_key=True, max_length=8)
fld2 = models.TextField()
fld3 = models.SlugField(unique=True, db_index=True, max_length=100)
I can create new records for this model without any issue. However, when I try to edit an already existing record via the Django admin interface (e.g., change the text field fld2), Django throws this error:
website_category with this fld3 already exists
I can delete said record and re-enter the modified one without any issues, and I can edit the record if I change the slug field but not otherwise.
My guess is this is happening due to the "unique=True" parameter set in the slug field (fld3). However, I do want the slugs to be unique.
Is this an expected behavior of Django, or can I do something to make it possible for me to edit the records directly without having to delete and recreate them?
====
Edit: Additional Info
the model does not have any custom save method or ModelAdmin class. It is registered simply via admin.site.register(). The model does have a meta class which is being used to define some DB level constraints:
class Meta:
constraints = [
models.CheckConstraint(check=models.Q(fld1__iregex = r'^\w{8}$'),
name="%(app_label)s_%(class)s_id_validator"),
models.CheckConstraint(check=models.Q(fld3__iregex = r'^[\w-]+$'),
name="%(app_label)s_%(class)s_slug_validator"),
# DB level condition to enforce slug format (word characters and '-')
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
