我需要一些帮助来自定义此错误。在此站点上已经可以看到我该如何更改模型表格的错误。我的问题是我只使用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!",
}
}
提前谢谢!
答案 0 :(得分:3)
这可能是您需要的。 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")
Nb:您可以使用任何字段代替self.user
答案 1 :(得分:-1)
为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)