Created
June 24, 2014 13:25
-
-
Save sebdah/ec2ae6cdf1723d365be6 to your computer and use it in GitHub Desktop.
Handling unique_together errors in Django forms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| myform.is_valid() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment