首页 > 解决方案 > Django:如何在管理端覆盖 unique_together 错误消息?

问题描述

我需要一些帮助来自定义此错误。已在此站点上看到如何更改模型表单的错误。我的问题是我使用纯粹的 django 管理端,我需要更改错误的外观。我也从 admin.py 将它们添加到我的 Class Meta 中,但什么也没发生!

在此处输入图像描述

当我将此代码放入模型中的 Class Meta 时,我收到此错误消息TypeError: 'class Meta' got invalid attribute(s): error_messages ,因此我的问题在这里。

请在下面找到我的模型:

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!",
             }
         }

先感谢您!

标签: djangocustom-errors

解决方案


这可能是您需要的。validate_unique 函数检查模型上的所有唯一性约束。将此功能放在您的 Parcare 模型中。

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

注意:您可以使用任何字段代替 self.user


推荐阅读