在这里,您可以找到一个与注释中的链接中给出的示例类似的最小工作示例。您只需小心不要将软验证包括在
clean_MagicNumber(self)
而是使用覆盖的
clean(self)
validate_unique(self)
作用
from django.core.exceptions import ValidationError
from django.db import models
from django.contrib import admin
from django import forms
from django.db import models
class Autor(models.Model):
Name = models.CharField(max_length=64)
MagicNumber = models.IntegerField()
class AutorAdminForm(forms.ModelForm):
ConfirmMagicNumber = forms.BooleanField(label="I confirm it is the right magic number.",
required=False,
widget=forms.HiddenInput)
def _field_is_active(self, field):
if self._meta.exclude is not None and field in self._meta.exclude:
return False
if self._meta.fields is not None and field in self._meta.fields:
return True
return False
def clean_MagicNumber(self):
if self.cleaned_data['MagicNumber'] < 100 or self.cleaned_data['MagicNumber'] > 1000:
raise ValidationError("Magic number outside of allowed range between 100 to 1000.")
return self.cleaned_data['MagicNumber']
def validate_unique(self):
"""
We use validate unique because it is quite late in the validation process,
after we got the values of all fields and
actually I used it, because I was really warning for a possible duplicate
"""
super().validate_unique()
# only check if number does not have errors and is in form data
if 'MagicNumber' not in self._errors and 'MagicNumber':
# only check if confirm checkbox is given and not checked
if ('ConfirmMagicNumber' in self.cleaned_data and 'ConfirmMagicNumber' in self.fields
and self.cleaned_data['ConfirmMagicNumber'] is not True and self._field_is_active('ConfirmMagicNumber')):
if self.cleaned_data['MagicNumber'] not in (100, 200, 381, 525, 1000):
error_msg = "The magic number looks wrong. Please confirm it below."
self.add_error('MagicNumber', error_msg)
self.fields['ConfirmMagicNumber'].widget = forms.CheckboxInput()
self.fields['ConfirmMagicNumber'].required = True
@admin.register(Autor)
class AutorAdmin(admin.ModelAdmin):
form = AutorAdminForm