I am trying to override the validate_unique for on of my models to validate that a record doesn't exist with duplicate fields (labeler, date), but It's not raising any validation error when i enter duplicate (labeler, date).
I've already looked through the issues here and here and constructed my view and model as follows:
my view:
class AttendanceCreateView(CreateView):
model = Attendance
template_name = "attendance/attendance_form.html"
fields = [
"team_lead",
"labeler",
"attendance",
]
def get_success_url(self):
return reverse("attendance-home")
my model:
class Attendance(models.Model):
id= models.AutoField(primary_key=True)
attendance = models.IntegerField(blank=True, choices= CHOICES_ATTENDANCE, null=True)
labeler = models.ForeignKey('Labelers', models.CASCADE, blank=True, null=True)
team_lead = models.ForeignKey('TeamLeads', models.CASCADE, blank=True, null=True)
date = models.DateField(auto_now_add=True, null=True)
class Meta:
managed = False
db_table = "attendance"
def validate_unique(self, *args, **kwargs):
super().validate_unique(*args, **kwargs)
if self.__class__.objects.filter(labeler= self.labeler, date= self.date).exists():
raise ValidationError(message='a already record exists for date and labeler',)
any idea why my code is not behaving as expected ? thanks is advance.