Search code examples
djangocustom-errors

Django: How to override unique_together error message on Admin Side?


I need some help to customize this error. Seen already on this site how can i change the error for the Model Form. My issue is that i use purely django admin side and i need to change how the error looks. I've added them also in my Class Meta from the admin.py and nothing happen!

enter image description here

When i put this code to my Class Meta in my models i receive this error message TypeError: 'class Meta' got invalid attribute(s): error_messages therefore my question here.

Please find below my models:

from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from datetime import datetime, timedelta, time
from django.core.exceptions import NON_FIELD_ERRORS

class Parcare(models.Model):
    PARKING_PLOT = (('P1', 'Parking #1'), ('P2', 'Parking #2'),('P3', 'Parking #3'))
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,null=True, default=1, on_delete=True)
    email=models.EmailField(blank=True, null=True)
    parking_on = models.DateField(auto_now=False, auto_now_add=False,blank=True, null=True,
                                  help_text='Alege data cand doresti sa vii in office',)
    parking_off = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, 
                                help_text='Alege Data Plecarii')  
    numar_masina = models.CharField(max_length=8, default="IF77WXV",blank=True, null=True, 
                                help_text='Introdu Numarul Masinii')
    location = models.CharField(max_length=3, blank=True, default="P1",null=True, choices=PARKING_PLOT,
                                help_text='Alege Locul de Parcare Dorit')
    updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True)
    timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True)
    venire = models.TimeField(default=time(9, 00), auto_now=False,auto_now_add=False, help_text='Alege Ora Venirii')
    plecare = models.TimeField(default=time(18, 00), auto_now=False, auto_now_add=False, help_text='Alege Ora Plecarii')
    # booked = models.BooleanField(default=1)
    objects = ParcareManager()

    def __str__(self):
        return self.location + " | " + str(self.parking_on) + " | " + str(self.parking_off)
    class Meta:
        verbose_name_plural = "parcare"
        ordering = ["-parking_on"]
        unique_together = ("parking_on", "location")
         error_messages = {
             NON_FIELD_ERRORS: {
                 'unique_together': "%(model_name)s's %(field_labels)s are not unique. This means that the same parking plot is already booked during time period!",
             }
         }

Thank you in advance!


Solution

  • This might be what you need. The validate_unique function checks for all the uniqueness constraints on your model. Place this function inside your Parcare Model.

    def validate_unique(self,exclude=None):
            try:
                super(Parcare,self).validate_unique()
            except ValidationError as e:
                raise ValidationError(self.user+"your message")
    

    Nb:You can use any field instead of self.user