Ticket #34296: unique_constraint.diff

File unique_constraint.diff, 2.0 KB (added by Jannis Vajen, 17 months ago)

Test to reproduce the issue

  • tests/inline_formsets/models.py

    diff --git a/tests/inline_formsets/models.py b/tests/inline_formsets/models.py
    index f4c06e8fac..096b77f8b3 100644
    a b class Poem(models.Model):  
    3232
    3333    def __str__(self):
    3434        return self.name
     35
     36
     37class Book(models.Model):
     38    poet = models.ForeignKey(Poet, models.CASCADE)
     39    name = models.CharField(max_length=100)
     40
     41    class Meta:
     42        constraints = [
     43            models.UniqueConstraint("poet", "name", name="unique_together_poet_name")
     44        ]
     45
     46    def __str__(self):
     47        return self.name
  • tests/inline_formsets/tests.py

    diff --git a/tests/inline_formsets/tests.py b/tests/inline_formsets/tests.py
    index 1ae9b3f760..cb6521ca79 100644
    a b  
    11from django.forms.models import ModelForm, inlineformset_factory
    22from django.test import TestCase, skipUnlessDBFeature
    33
    4 from .models import Child, Parent, Poem, Poet, School
     4from .models import Book, Child, Parent, Poem, Poet, School
    55
    66
    77class DeletionTests(TestCase):
    class InlineFormsetFactoryTest(TestCase):  
    184184            formset.non_form_errors(), ["Please correct the duplicate data for name."]
    185185        )
    186186
     187    def test_unique_constraint_validation_error(self):
     188        poet = Poet.objects.create(name="Poet")
     189        BookFormSet = inlineformset_factory(Poet, Book, fields=["name"])
     190        data = {
     191            "book_set-TOTAL_FORMS": "2",
     192            "book_set-INITIAL_FORMS": "0",
     193            "book_set-MAX_NUM_FORMS": "2",
     194            "book_set-0-name": "A Book",
     195            "book_set-1-name": "A Book",
     196        }
     197        formset = BookFormSet(data, instance=poet)
     198        self.assertFalse(formset.is_valid())
     199        self.assertEqual(
     200            formset.non_form_errors(), ["Please correct the duplicate data for name."]
     201        )
     202
    187203    def test_fk_not_duplicated_in_form_fields(self):
    188204        """
    189205        A foreign key name isn't duplicated in form._meta fields (#21332).
Back to Top