【问题标题】:Django: How to override unique_together error message on Admin Side?Django:如何在管理端覆盖 unique_together 错误消息?
【发布时间】:2018-09-23 20:25:32
【问题描述】:

我需要一些帮助来自定义此错误。已在此站点上看到如何更改模型表单的错误。我的问题是我使用纯粹的 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!",
             }
         }

提前谢谢你!

【问题讨论】:

  • 您是否正在寻找修改错误信息的方法?
  • 是的阿布吉特!谢谢!我想自定义一个更好的错误消息,因为用户将没有它的背景!

标签: django custom-errors


【解决方案1】:

这可能是您需要的。 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

【讨论】:

    【解决方案2】:

    unique_together定义一个overrides the error message的模型表单:

    class ParcareForm(forms.ModelForm):
        class Meta:
            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!",
                },
            }
    

    然后通过设置form 告诉您的模型管理员类给我们您的模型表单:

    class ParcareAdmin(admin.ModelAdmin):
        form = ParcareForm
    
    admin.register(Parcare, ParcareAdmin)
    

    【讨论】:

    • 我必须在这个表单下面放一个 Meta 类?
    • 对不起,我不明白你的问题。您在问题中说您已经了解如何更改模型表单的错误。
    • 是的,但我没有在我的代码中使用模型表单...我只有模型和管理员。这就是我问的原因
    • 从您的问题来看,您似乎已经知道如何为模型表单自定义错误消息,所以我省略了那部分。我现在在答案中添加了一个示例模型表单。
    猜你喜欢
    • 2011-04-28
    • 2011-07-15
    • 2023-03-31
    • 2023-01-07
    • 2020-08-12
    • 2012-10-18
    • 2010-12-01
    • 2014-03-11
    • 1970-01-01
    相关资源
    最近更新 更多