Authenticating unique Django models on a form

I have a model with several unique fields and I am writing a form for it. I found some reference to a method [validate_unique][1]

that should check for uniqueness of fields when called, but my form .is_valid()

always returns True

.

My test file:

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 )

      

+3


source to share


2 answers


validate_unique is a method Model

.

The superclass method run clean

should take care of the model's given uniqueness checks ModelForm

.



class MyModelForm(forms.ModelForm):    
    def clean(self):
        cleaned_data = super(MyModelForm, self).clean()
        # additional cleaning here
        return cleaned_data

      

There is a warning in the django docs, specifically about overriding cleanup with ModelForm

s, which automatically performs several steps of model validation.

+6


source


I solve it by adding validate_unique()

tosave()

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) 

      



This works for me. I don't know about you.

0


source







All Articles