Skip to content

Instantly share code, notes, and snippets.

@sebdah
Created June 24, 2014 13:25
Show Gist options
  • Select an option

  • Save sebdah/ec2ae6cdf1723d365be6 to your computer and use it in GitHub Desktop.

Select an option

Save sebdah/ec2ae6cdf1723d365be6 to your computer and use it in GitHub Desktop.
Handling unique_together errors in Django forms
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('field2', 'field3', 'field4', 'field5')
def clean(self):
"""
Clean MyModel
"""
# Get the cleaned data
cleaned_data = self.cleaned_data
# Find the unique_together fields
field1 = cleaned_data.get('instance')
field2 = cleaned_data.get('data_file')
field3 = cleaned_data.get('column')
field4 = cleaned_data.get('key')
objects = MyModel.objects.filter( field1 = field1,
field2 = field2,
field3 = field3,
field4 = field4)
if len(objects) > 0:
msg = u"This row is not unique"
self._errors["field1"] = self.error_class([msg])
del cleaned_data["field1"]
raise ValidationError(msg)
return cleaned_data
from django import forms
class MyModel(models.Model):
class Meta:
unique_together = ('field1', 'field2', 'field3', 'field4')
field1 = models.ForeignKey(MyModel)
field2 = models.CharField(null = False, max_length = 30)
field3 = models.CharField(null = False, max_length = 30)
field4 = models.CharField(null = False, max_length = 30)
field5 = models.CharField(null = False, max_length = 80)
myform.is_valid()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment