I recently had a situation where the validate_unique method from my model wasn't running. This is because one of the fields involved in the unique test wasn't included in the form. I tried many things in the form and the view before landing on this solution: I first injected the field into the object of the UpdateView, then ran the test in the Form in _post_clean.
models.py
class Link(ModelBase):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=200,blank=True,null=False)
url = models.URLField(max_length=400,blank=False,null=False)
profile = models.ForeignKey('Profile',null=False,blank=False,on_delete=models.CASCADE)
class Meta:
unique_together = ('url','profile')
class Admin:
pass
forms.py
class LinkForm(ModelForm):
def _post_clean(self):
''' Be sure that the instance validate_unique test
is run including the profile field '''
super(LinkForm,self)._post_clean()
try:
self.instance.validate_unique(exclude=None)
except ValidationError as e:
self._update_errors(e)
class Meta:
model = Link
fields = ['title','url']
views.py
class LinkUpdateView(UpdateView):
model = Link
form_class = LinkForm
def get_form_kwargs(self):
''' Add profile to self.object before kwargs are populated '''
if hasattr(self, 'object') and self.object and self.profile:
self.object.profile = profile
kwargs = super(LinkUpdateView, self).get_form_kwargs()
return kwargs
Is there a better way to do this that doesn't involve overriding an internal function?