问题
I have a model with a few unique fields and I'm writing a form for it. I found some reference to the [validate_unique][1]
method that should check for uniqueness on fields when you call it but my form .is_valid()
always returns True
.
My testcase:
class ServerFormTest( TestCase ):
def setUp( self ):
self.server = Server.objects.create( host = "127.0.0.1", name = "localhost" )
def test_unique_name(self):
form = ServerForm({
'name': 'localhost',
'host': '127.0.0.1'
})
self.assertFalse( form.is_valid( ) )
and my form:
class ServerForm( forms.ModelForm ):
class Meta:
model = Server
fields = ('name', 'host')
def clean( self ):
self.validate_unique()
return self.cleaned_data
server model:
class Server( models.Model ):
host = models.GenericIPAddressField( blank = False, null = False, unique = True )
name = models.CharField( blank = False, null = False, unique = True, max_length = 55 )
回答1:
validate_unique is a Model
method.
Running the superclass clean
method should take care of model uniqueness checks given a ModelForm
.
class MyModelForm(forms.ModelForm):
def clean(self):
cleaned_data = super(MyModelForm, self).clean()
# additional cleaning here
return cleaned_data
There is a warning on the django docs specifically about overriding clean on ModelForm
s, which automatically does several model validation steps.
回答2:
I solve it by adding validate_unique()
to save()
class Server( models.Model ):
host = models.GenericIPAddressField( blank = False, null = False, unique = True )
name = models.CharField( blank = False, null = False, unique = True, max_length = 55 )
def save(self, *args,**kwargs):
self.validate_unique()
super(Server,self).save(*args, **kwargs)
It works for me. I don't know about you.
来源:https://stackoverflow.com/questions/31150929/django-unique-model-fields-validation-in-form