I'm trying to use unique_for_date option to prevent creating multiple posts with the same slug for the same date. But it doesn't seem to work at all: I still can create posts with the same slug from the shell and admin dashboard. The same goes for ModelForm. My models.py:
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
('suspended', 'Suspended'),
)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique_for_date='created')
status = models.CharField(max_length=15,
choices=STATUS_CHOICES,
default='draft')
content = models.TextField(max_length=200000, blank=True)
# dates
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
publish = models.DateTimeField(default=timezone.now)
I've found some kind of a workaround for problem by changing auto_now_add=True to default=timezone.now but it only shows error while creating object via django admin - still no errors while creating objects from shell or form.
Update: I know that using auto_now_add sets editable=False causing django to skip field validation, but it doesn't explain why it skips validation even with default=timezone.now
Update 2: For some reason unique_for_date works only for django-admin dashboard forms (in my case at least). To get the same effect for other forms I've overridden the clean_fields method of the model (forces django to validate unique fields):
def clean_fields(self, exclude=None):
super().clean_fields(exclude=exclude)
self.validate_unique()