0

I have a model in Django as follows

class TwoPlanetKeyword(models.Model):
    planet_one = models.ForeignKey(Planet, related_name="planet_one")
    planet_two = models.ForeignKey(Planet, related_name="planet_two")
    keyword_list = models.TextField(max_length=100000)

    class Meta:
        verbose_name = 'Keywords for Two Planet Combination'
        unique_together = ['planet_one', 'planet_two']

    def __str__(self):
        return "Keywords for two planet combination of {} and {}".format(self.planet_one, self.planet_two)

    def clean(self, *args, **kwargs):
        plan_one = self.planet_one
        plan_two = self.planet_two
        try:
            obj_val = TwoPlanetKeyword.objects.get(Q(planet_one=plan_one, planet_two=plan_two) | Q(planet_one=plan_two, planet_two=plan_one))
            raise ValidationError({
                        NON_FIELD_ERRORS: [
                            'This combination exists',
                        ],
                    })
        except TwoPlanetKeyword.DoesNotExist:
            super(TwoPlanetKeyword, self).clean(*args, **kwargs)

    def full_clean(self, *args, **kwargs):
        return self.clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(MyModel, self).save(*args, **kwargs)

The idea here is that to basically prevent permutations of fields in the table from being entered as detailed here Prevent permutations of foreign keys in Django.

This solves the above problem but it gives me a clean() got an unexpected keyword argument 'validate_unique' error when I try to save new entries in the table in Django Admin

Community
  • 1
  • 1
Newtt
  • 6,050
  • 13
  • 68
  • 106

1 Answers1

5

You should remove the full_clean method. It wasn't really designed to be overridden. The idea is that you write a custom clean method (as you have done) and then when you call obj.full_clean(), the base implementation will call obj.clean() for you.

Note that clean() does not take any args or kwargs, so you can remove them from the signature. Your error is because you were passing the validate_unique keyword argument from full_clean to the superclass' clean method.

def clean(self):
   ...
   super(TwoPlanetKeyword, self).clean()

See the docs on validating objects for more details.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • See [my previous answer](http://stackoverflow.com/questions/12945339/is-this-the-way-to-validate-django-model-fields/12945692#12945692) about whether or not you want to call `full_clean` in the save method. – Alasdair Aug 02 '15 at 21:58