def test_commit(self):
        # The commit parameter will instruct the method to save the child objects straight away

        self.beatles.save()
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.save()

        child_object_mapping = self.beatles.copy_child_relation('members',
                                                                beatles_clone,
                                                                commit=True)

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        self.assertIsNotNone(new_john.pk)
        self.assertIsNotNone(new_paul.pk)
        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, john.pk): new_john,
                (band_members_rel, paul.pk): new_paul,
            })
Esempio n. 2
0
    def test_child_updates_without_ids(self):
        first_song = Song(name='I Saw Her Standing There')
        album = Album(name='Please Please Me', songs=[first_song])
        beatles = Band(name='The Beatles', albums=[album])
        beatles.save()

        first_song_id = first_song.id

        second_song = Song(name='Misery')
        album.songs.add(second_song)

        AlbumsFormset = childformset_factory(Band, Album, form=ClusterForm, extra=3)

        albums_formset = AlbumsFormset({
            'form-TOTAL_FORMS': 1,
            'form-INITIAL_FORMS': 1,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'Please Please Me',
            'form-0-id': album.id,

            'form-0-songs-TOTAL_FORMS': 2,
            'form-0-songs-INITIAL_FORMS': 2,
            'form-0-songs-MAX_NUM_FORMS': 1000,

            'form-0-songs-0-name': 'I Saw Her Standing There',
            'form-0-songs-0-id': first_song_id,

            'form-0-songs-1-name': 'Misery',
            'form-0-songs-1-id': '',
        }, instance=beatles)

        self.assertTrue(albums_formset.is_valid())
        albums_formset.save(commit=False)
        self.assertEqual(2, beatles.albums.first().songs.count())
    def test_child_updates_without_ids(self):
        john = BandMember(name='John Lennon')
        beatles = Band(name='The Beatles', members=[
            john
        ])
        beatles.save()
        john_id = john.id

        paul = BandMember(name='Paul McCartney')
        beatles.members.add(paul)

        BandMembersFormset = childformset_factory(Band, BandMember, extra=3)
        band_members_formset = BandMembersFormset({
            'form-TOTAL_FORMS': 2,
            'form-INITIAL_FORMS': 2,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'John Lennon',
            'form-0-id': john_id,

            'form-1-name': 'Paul McCartney',  # NB no way to know programmatically that this form corresponds to the 'paul' object
            'form-1-id': '',
        }, instance=beatles)

        self.assertTrue(band_members_formset.is_valid())
        band_members_formset.save(commit=False)
        self.assertEqual(2, beatles.members.count())
    def test_copy_child_relations_between_saved_objects(self):
        # This test copies child relations between two saved objects
        # This also shouldn't commit the new child objects to the database

        self.beatles.save()
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.save()

        child_object_mapping = self.beatles.copy_child_relation(
            'members', beatles_clone)

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        self.assertIsNone(new_john.pk)
        self.assertIsNone(new_paul.pk)
        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, john.pk): new_john,
                (band_members_rel, paul.pk): new_paul,
            })
    def test_copy_child_relations_from_unsaved_to_saved_object(self):
        # This test copies unsaved child relations into a saved object.
        # This shouldn't commit the new child objects to the database

        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.save()

        child_object_mapping = self.beatles.copy_child_relation(
            'members', beatles_clone)

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        self.assertIsNone(new_john.pk)
        self.assertIsNone(new_paul.pk)
        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)

        self.assertEqual(child_object_mapping, {
            (band_members_rel, None): [new_john, new_paul],
        })

        # Bonus test! Let's save the clone again, and see if we can access the new PKs from child_object_mapping
        # (Django should mutate the objects we already have when we save them)
        beatles_clone.save()
        self.assertTrue(child_object_mapping[(band_members_rel, None)][0].pk)
        self.assertTrue(child_object_mapping[(band_members_rel, None)][1].pk)
    def test_append(self):
        # But you can specify append=True, which appends them to the existing list

        self.beatles.save()
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.members.add(BandMember(name='Julian Lennon'))
        beatles_clone.save()

        self.assertTrue(
            beatles_clone.members.filter(name='Julian Lennon').exists())

        child_object_mapping = self.beatles.copy_child_relation('members',
                                                                beatles_clone,
                                                                append=True)

        self.assertTrue(
            beatles_clone.members.filter(name='Julian Lennon').exists())

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        self.assertIsNone(new_john.pk)
        self.assertIsNone(new_paul.pk)
        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, john.pk): new_john,
                (band_members_rel, paul.pk): new_paul,
            })
    def test_child_updates_without_ids(self):
        john = BandMember(name='John Lennon')
        beatles = Band(name='The Beatles', members=[
            john
        ])
        beatles.save()
        john_id = john.id

        paul = BandMember(name='Paul McCartney')
        beatles.members.add(paul)

        BandMembersFormset = childformset_factory(Band, BandMember, extra=3)
        band_members_formset = BandMembersFormset({
            'form-TOTAL_FORMS': 2,
            'form-INITIAL_FORMS': 2,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'John Lennon',
            'form-0-id': john_id,

            'form-1-name': 'Paul McCartney',  # NB no way to know programmatically that this form corresponds to the 'paul' object
            'form-1-id': '',
        }, instance=beatles)

        self.assertTrue(band_members_formset.is_valid())
        band_members_formset.save(commit=False)
        self.assertEqual(2, beatles.members.count())
Esempio n. 8
0
    def test_queryset_filtering(self):
        beatles = Band(name='The Beatles',
                       members=[
                           BandMember(id=1, name='John Lennon'),
                           BandMember(id=2, name='Paul McCartney'),
                       ])
        self.assertEqual('Paul McCartney', beatles.members.get(id=2).name)
        self.assertEqual('Paul McCartney', beatles.members.get(id='2').name)
        self.assertEqual(1,
                         beatles.members.filter(name='Paul McCartney').count())

        # also need to be able to filter on foreign fields that return a model instance
        # rather than a simple python value
        self.assertEqual(2, beatles.members.filter(band=beatles).count())
        # and ensure that the comparison is not treating all unsaved instances as identical
        rutles = Band(name='The Rutles')
        self.assertEqual(0, beatles.members.filter(band=rutles).count())

        # and the comparison must be on the model instance's ID where available,
        # not by reference
        beatles.save()
        beatles.members.add(
            BandMember(id=3, name='George Harrison')
        )  # modify the relation so that we're not to a plain database-backed queryset

        also_beatles = Band.objects.get(id=beatles.id)
        self.assertEqual(3, beatles.members.filter(band=also_beatles).count())
Esempio n. 9
0
    def test_save_commit_false(self):
        first_song = Song(name='I Saw Her Standing There')
        second_song = Song(name='Mystery')
        album = Album(name='Please Please Me', songs=[first_song, second_song])
        beatles = Band(name='The Beatles', albums=[album])
        beatles.save()
        first_song_id, second_song_id = first_song.id, second_song.id

        AlbumsFormset = childformset_factory(Band, Album, form=ClusterForm, extra=3)

        albums_formset = AlbumsFormset({
            'form-TOTAL_FORMS': 1,
            'form-INITIAL_FORMS': 1,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'Please Please Me',
            'form-0-id': album.id,

            'form-0-songs-TOTAL_FORMS': 4,
            'form-0-songs-INITIAL_FORMS': 2,
            'form-0-songs-MAX_NUM_FORMS': 1000,

            'form-0-songs-0-name': 'I Saw Her Standing There',
            'form-0-songs-0-DELETE': 'form-0-songs-0-DELETE',
            'form-0-songs-0-id': first_song_id,

            'form-0-songs-1-name': 'Misery',  # changing data of an existing record
            'form-0-songs-1-id': second_song_id,

            'form-0-songs-2-name': '',
            'form-0-songs-2-id': '',

            'form-0-songs-3-name': 'Chains',  # adding a record
            'form-0-songs-3-id': '',
        }, instance=beatles)
        self.assertTrue(albums_formset.is_valid())
        updated_albums = albums_formset.save(commit=False)

        # updated_members should only include the items that have been changed and not deleted
        self.assertEqual(1, len(updated_albums))
        self.assertEqual('Please Please Me', updated_albums[0].name)
        self.assertEqual(2, updated_albums[0].songs.count())
        self.assertEqual('Misery', updated_albums[0].songs.first().name)
        self.assertEqual(second_song_id, updated_albums[0].songs.first().id)

        self.assertEqual('Chains', updated_albums[0].songs.all()[1].name)
        self.assertEqual(None, updated_albums[0].songs.all()[1].id)

        # Changes should not be committed to the db yet
        self.assertTrue(Song.objects.filter(name='I Saw Her Standing There', id=first_song_id).exists())
        self.assertEqual('Mystery', Song.objects.get(id=second_song_id).name)
        self.assertFalse(Song.objects.filter(name='Chains').exists())

        beatles.albums.first().songs.commit()
        # this should create/update/delete database entries
        self.assertEqual('Misery', Song.objects.get(id=second_song_id).name)
        self.assertTrue(Song.objects.filter(name='Chains').exists())
        self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
    def test_ignore_validation_on_deleted_items(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        please_please_me = Album(name='Please Please Me',
                                 release_date=datetime.date(1963, 3, 22))
        beatles = Band(name='The Beatles', albums=[please_please_me])
        beatles.save()

        form = BandForm(
            {
                'name': "The Beatles",
                'members-TOTAL_FORMS': 0,
                'members-INITIAL_FORMS': 0,
                'members-MAX_NUM_FORMS': 1000,
                'albums-TOTAL_FORMS': 1,
                'albums-INITIAL_FORMS': 1,
                'albums-MAX_NUM_FORMS': 1000,
                'albums-0-name': 'With The Beatles',
                'albums-0-release_date': '1963-02-31',  # invalid date
                'albums-0-id': please_please_me.id,
                'albums-0-ORDER': 1,
                'albums-0-songs-TOTAL_FORMS': 0,
                'albums-0-songs-INITIAL_FORMS': 0,
                'albums-0-songs-MAX_NUM_FORMS': 1000,
            },
            instance=beatles)

        self.assertFalse(form.is_valid())

        form = BandForm(
            {
                'name': "The Beatles",
                'members-TOTAL_FORMS': 0,
                'members-INITIAL_FORMS': 0,
                'members-MAX_NUM_FORMS': 1000,
                'albums-TOTAL_FORMS': 1,
                'albums-INITIAL_FORMS': 1,
                'albums-MAX_NUM_FORMS': 1000,
                'albums-0-name': 'With The Beatles',
                'albums-0-release_date': '1963-02-31',  # invalid date
                'albums-0-id': please_please_me.id,
                'albums-0-ORDER': 1,
                'albums-0-DELETE': 'albums-0-DELETE',
                'albums-0-songs-TOTAL_FORMS': 0,
                'albums-0-songs-INITIAL_FORMS': 0,
                'albums-0-songs-MAX_NUM_FORMS': 1000,
            },
            instance=beatles)

        self.assertTrue(form.is_valid())
        form.save(commit=False)
        self.assertEqual(0, beatles.albums.count())
        self.assertEqual(1, Band.objects.get(id=beatles.id).albums.count())
        beatles.save()
        self.assertEqual(0, Band.objects.get(id=beatles.id).albums.count())
Esempio n. 11
0
    def test_incoming_form_data(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        beatles = Band(name='The Beatles', albums=[
            Album(name='Please Please Me', songs=[
                Song(name='I Saw Her Standing There')
            ]),
        ])
        form = BandForm({
            'name': 'The Beatles',

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': 'Please Please Me',
            'albums-0-id': '',
            'albums-0-ORDER': 1,

            'albums-0-songs-TOTAL_FORMS': 2,
            'albums-0-songs-INITIAL_FORMS': 1,
            'albums-0-songs-MAX_NUM_FORMS': 1000,

            'albums-0-songs-0-name': 'I Saw Her Standing There',
            'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE',
            'albums-0-songs-0-id': '',

            'albums-0-songs-1-name': 'Misery',
            'albums-0-songs-1-id': '',
        }, instance=beatles)

        self.assertTrue(form.is_valid())
        result = form.save(commit=False)
        self.assertEqual(result, beatles)

        self.assertEqual(1, beatles.albums.count())
        self.assertEqual('Please Please Me', beatles.albums.first().name)

        self.assertEqual(1, beatles.albums.first().songs.all().count())
        self.assertEqual('Misery', beatles.albums.first().songs.first().name)

        # should not exist in the database yet
        self.assertFalse(Album.objects.filter(name='Please Please Me').exists())
        self.assertFalse(Song.objects.filter(name='Misery').exists())

        beatles.save()
        # this should create database entries
        self.assertTrue(Band.objects.filter(name='The Beatles').exists())
        self.assertTrue(Album.objects.filter(name='Please Please Me').exists())
        self.assertTrue(Song.objects.filter(name='Misery').exists())
        self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
    def test_incoming_form_data(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        beatles = Band(name='The Beatles', albums=[
            Album(name='Please Please Me', songs=[
                Song(name='I Saw Her Standing There')
            ]),
        ])
        form = BandForm({
            'name': 'The Beatles',

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': 'Please Please Me',
            'albums-0-id': '',
            'albums-0-ORDER': 1,

            'albums-0-songs-TOTAL_FORMS': 2,
            'albums-0-songs-INITIAL_FORMS': 1,
            'albums-0-songs-MAX_NUM_FORMS': 1000,

            'albums-0-songs-0-name': 'I Saw Her Standing There',
            'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE',
            'albums-0-songs-0-id': '',

            'albums-0-songs-1-name': 'Misery',
            'albums-0-songs-1-id': '',
        }, instance=beatles)

        self.assertTrue(form.is_valid())
        result = form.save(commit=False)
        self.assertEqual(result, beatles)

        self.assertEqual(1, beatles.albums.count())
        self.assertEqual('Please Please Me', beatles.albums.first().name)

        self.assertEqual(1, beatles.albums.first().songs.all().count())
        self.assertEqual('Misery', beatles.albums.first().songs.first().name)

        # should not exist in the database yet
        self.assertFalse(Album.objects.filter(name='Please Please Me').exists())
        self.assertFalse(Song.objects.filter(name='Misery').exists())

        beatles.save()
        # this should create database entries
        self.assertTrue(Band.objects.filter(name='The Beatles').exists())
        self.assertTrue(Album.objects.filter(name='Please Please Me').exists())
        self.assertTrue(Song.objects.filter(name='Misery').exists())
        self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
    def test_can_create_cluster(self):
        beatles = Band(name='The Beatles')

        self.assertEqual(0, beatles.members.count())

        beatles.members = [
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ]

        # we should be able to query this relation using (some) queryset methods
        self.assertEqual(2, beatles.members.count())
        self.assertEqual('John Lennon', beatles.members.all()[0].name)
        self.assertEqual('Paul McCartney', beatles.members.filter(name='Paul McCartney')[0].name)
        self.assertEqual('Paul McCartney', beatles.members.get(name='Paul McCartney').name)
        self.assertRaises(BandMember.DoesNotExist, lambda: beatles.members.get(name='Reginald Dwight'))
        self.assertRaises(BandMember.MultipleObjectsReturned, lambda: beatles.members.get())

        self.assertEqual([('Paul McCartney',)], beatles.members.filter(name='Paul McCartney').values_list('name'))
        self.assertEqual(['Paul McCartney'], beatles.members.filter(name='Paul McCartney').values_list('name', flat=True))
        # quick-and-dirty check that we can invoke values_list with empty args list
        beatles.members.filter(name='Paul McCartney').values_list()

        self.assertTrue(beatles.members.filter(name='Paul McCartney').exists())
        self.assertFalse(beatles.members.filter(name='Reginald Dwight').exists())

        self.assertEqual('John Lennon', beatles.members.first().name)
        self.assertEqual('Paul McCartney', beatles.members.last().name)

        self.assertTrue('John Lennon', beatles.members.order_by('name').first())
        self.assertTrue('Paul McCartney', beatles.members.order_by('-name').first())

        # these should not exist in the database yet
        self.assertFalse(Band.objects.filter(name='The Beatles').exists())
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())

        beatles.save()
        # this should create database entries
        self.assertTrue(Band.objects.filter(name='The Beatles').exists())
        self.assertTrue(BandMember.objects.filter(name='John Lennon').exists())

        john_lennon = BandMember.objects.get(name='John Lennon')
        beatles.members = [john_lennon]
        # reassigning should take effect on the in-memory record
        self.assertEqual(1, beatles.members.count())
        # but not the database
        self.assertEqual(2, Band.objects.get(name='The Beatles').members.count())

        beatles.save()
        # now updated in the database
        self.assertEqual(1, Band.objects.get(name='The Beatles').members.count())
        self.assertEqual(1, BandMember.objects.filter(name='John Lennon').count())
        # removed member should be deleted from the db entirely
        self.assertEqual(0, BandMember.objects.filter(name='Paul McCartney').count())

        # queries on beatles.members should now revert to SQL
        self.assertTrue(beatles.members.extra(where=["tests_bandmember.name='John Lennon'"]).exists())
    def test_can_only_commit_on_saved_parent(self):
        beatles = Band(name='The Beatles', members=[
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ])
        self.assertRaises(IntegrityError, lambda: beatles.members.commit())

        beatles.save()
        beatles.members.commit()
    def test_can_create_cluster(self):
        beatles = Band(name='The Beatles')

        self.assertEqual(0, beatles.members.count())

        beatles.members = [
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ]

        # we should be able to query this relation using (some) queryset methods
        self.assertEqual(2, beatles.members.count())
        self.assertEqual('John Lennon', beatles.members.all()[0].name)
        self.assertEqual('Paul McCartney', beatles.members.filter(name='Paul McCartney')[0].name)
        self.assertEqual('Paul McCartney', beatles.members.get(name='Paul McCartney').name)
        self.assertRaises(BandMember.DoesNotExist, lambda: beatles.members.get(name='Reginald Dwight'))
        self.assertRaises(BandMember.MultipleObjectsReturned, lambda: beatles.members.get())

        self.assertEqual([('Paul McCartney',)], beatles.members.filter(name='Paul McCartney').values_list('name'))
        self.assertEqual(['Paul McCartney'], beatles.members.filter(name='Paul McCartney').values_list('name', flat=True))
        # quick-and-dirty check that we can invoke values_list with empty args list
        beatles.members.filter(name='Paul McCartney').values_list()

        self.assertTrue(beatles.members.filter(name='Paul McCartney').exists())
        self.assertFalse(beatles.members.filter(name='Reginald Dwight').exists())

        self.assertEqual('John Lennon', beatles.members.first().name)
        self.assertEqual('Paul McCartney', beatles.members.last().name)

        self.assertTrue('John Lennon', beatles.members.order_by('name').first())
        self.assertTrue('Paul McCartney', beatles.members.order_by('-name').first())

        # these should not exist in the database yet
        self.assertFalse(Band.objects.filter(name='The Beatles').exists())
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())

        beatles.save()
        # this should create database entries
        self.assertTrue(Band.objects.filter(name='The Beatles').exists())
        self.assertTrue(BandMember.objects.filter(name='John Lennon').exists())

        john_lennon = BandMember.objects.get(name='John Lennon')
        beatles.members = [john_lennon]
        # reassigning should take effect on the in-memory record
        self.assertEqual(1, beatles.members.count())
        # but not the database
        self.assertEqual(2, Band.objects.get(name='The Beatles').members.count())

        beatles.save()
        # now updated in the database
        self.assertEqual(1, Band.objects.get(name='The Beatles').members.count())
        self.assertEqual(1, BandMember.objects.filter(name='John Lennon').count())
        # removed member should be deleted from the db entirely
        self.assertEqual(0, BandMember.objects.filter(name='Paul McCartney').count())

        # queries on beatles.members should now revert to SQL
        self.assertTrue(beatles.members.extra(where=["tests_bandmember.name='John Lennon'"]).exists())
    def test_can_only_commit_on_saved_parent(self):
        beatles = Band(name='The Beatles', members=[
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ])
        self.assertRaises(IntegrityError, lambda: beatles.members.commit())

        beatles.save()
        beatles.members.commit()
    def test_save_commit_false(self):
        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        ringo = BandMember(name='Richard Starkey')
        beatles = Band(name='The Beatles', members=[john, paul, ringo])
        beatles.save()
        john_id, paul_id, ringo_id = john.id, paul.id, ringo.id

        BandMembersFormset = childformset_factory(Band, BandMember, extra=3)

        band_members_formset = BandMembersFormset(
            {
                'form-TOTAL_FORMS': 5,
                'form-INITIAL_FORMS': 3,
                'form-MAX_NUM_FORMS': 1000,
                'form-0-name': 'John Lennon',
                'form-0-DELETE': 'form-0-DELETE',
                'form-0-id': john_id,
                'form-1-name': 'Paul McCartney',
                'form-1-id': paul_id,
                'form-2-name':
                'Ringo Starr',  # changing data of an existing record
                'form-2-id': ringo_id,
                'form-3-name': '',
                'form-3-id': '',
                'form-4-name': 'George Harrison',  # adding a record
                'form-4-id': '',
            },
            instance=beatles)
        self.assertTrue(band_members_formset.is_valid())
        updated_members = band_members_formset.save(commit=False)

        # updated_members should only include the items that have been changed and not deleted
        self.assertEqual(2, len(updated_members))
        self.assertEqual('Ringo Starr', updated_members[0].name)
        self.assertEqual(ringo_id, updated_members[0].id)

        self.assertEqual('George Harrison', updated_members[1].name)
        self.assertEqual(None, updated_members[1].id)

        # Changes should not be committed to the db yet
        self.assertTrue(
            BandMember.objects.filter(name='John Lennon', id=john_id).exists())
        self.assertEqual('Richard Starkey',
                         BandMember.objects.get(id=ringo_id).name)
        self.assertFalse(
            BandMember.objects.filter(name='George Harrison').exists())

        beatles.members.commit()
        # this should create/update/delete database entries
        self.assertEqual('Ringo Starr',
                         BandMember.objects.get(id=ringo_id).name)
        self.assertTrue(
            BandMember.objects.filter(name='George Harrison').exists())
        self.assertFalse(
            BandMember.objects.filter(name='John Lennon').exists())
Esempio n. 18
0
 def test_model_with_zero_pk(self):
     beatles = Band(name='The Beatles',
                    members=[
                        BandMember(name='John Lennon'),
                        BandMember(name='Paul McCartney'),
                    ])
     beatles.save()
     beatles.pk = 0
     beatles.members.commit()
     beatles.save()
Esempio n. 19
0
 def test_model_with_zero_pk(self):
     beatles = Band(name='The Beatles', members=[
         BandMember(name='John Lennon'),
         BandMember(name='Paul McCartney'),
     ])
     beatles.save()
     beatles.pk = 0
     beatles.members.commit()
     beatles.save()
     self.assertEqual(Band.objects.get(pk=0).name, 'The Beatles')
Esempio n. 20
0
    def test_saved_items(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        first_song = Song(name='I Saw Her Standing There')
        second_song = Song(name='Misery')
        album = Album(name='Please Please Me', songs=[first_song, second_song])
        beatles = Band(name='The Beatles', albums=[album])
        beatles.save()

        self.assertTrue(album.id)
        self.assertTrue(first_song.id)
        self.assertTrue(second_song.id)

        form = BandForm({
            'name': 'The Beatles',

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 1,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': album.name,
            'albums-0-id': album.id,
            'albums-0-ORDER': 1,

            'albums-0-songs-TOTAL_FORMS': 4,
            'albums-0-songs-INITIAL_FORMS': 2,
            'albums-0-songs-MAX_NUM_FORMS': 1000,

            'albums-0-songs-0-name': first_song.name,
            'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE',
            'albums-0-songs-0-id': first_song.id,

            'albums-0-songs-1-name': second_song.name,
            'albums-0-songs-1-id': second_song.id,

            'albums-0-songs-2-name': 'Anna',
            'albums-0-songs-2-id': '',

            'albums-0-songs-3-name': '',
            'albums-0-songs-3-id': '',
        }, instance=beatles)
        self.assertTrue(form.is_valid())
        form.save()

        self.assertTrue(Song.objects.filter(name='Anna').exists())
        self.assertTrue(Song.objects.filter(name='Misery').exists())
        self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
Esempio n. 21
0
 def test_integrity_error_with_none_pk(self):
     beatles = Band(name='The Beatles',
                    members=[
                        BandMember(name='John Lennon'),
                        BandMember(name='Paul McCartney'),
                    ])
     beatles.save()
     beatles.pk = None
     self.assertRaises(IntegrityError, lambda: beatles.members.commit())
     # this should work fine, as Django will end up cloning this entity
     beatles.save()
Esempio n. 22
0
    def test_save_commit_false(self):
        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        ringo = BandMember(name='Richard Starkey')
        beatles = Band(name='The Beatles', members=[
            john, paul, ringo
        ])
        beatles.save()
        john_id, paul_id, ringo_id = john.id, paul.id, ringo.id

        BandMembersFormset = childformset_factory(Band, BandMember, extra=3)

        band_members_formset = BandMembersFormset({
            'form-TOTAL_FORMS': 5,
            'form-INITIAL_FORMS': 3,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'John Lennon',
            'form-0-DELETE': 'form-0-DELETE',
            'form-0-id': john_id,

            'form-1-name': 'Paul McCartney',
            'form-1-id': paul_id,

            'form-2-name': 'Ringo Starr',  # changing data of an existing record
            'form-2-id': ringo_id,

            'form-3-name': '',
            'form-3-id': '',

            'form-4-name': 'George Harrison',  # adding a record
            'form-4-id': '',
        }, instance=beatles)
        self.assertTrue(band_members_formset.is_valid())
        updated_members = band_members_formset.save(commit=False)

        # updated_members should only include the items that have been changed and not deleted
        self.assertEqual(2, len(updated_members))
        self.assertEqual('Ringo Starr', updated_members[0].name)
        self.assertEqual(ringo_id, updated_members[0].id)

        self.assertEqual('George Harrison', updated_members[1].name)
        self.assertEqual(None, updated_members[1].id)

        # Changes should not be committed to the db yet
        self.assertTrue(BandMember.objects.filter(name='John Lennon', id=john_id).exists())
        self.assertEqual('Richard Starkey', BandMember.objects.get(id=ringo_id).name)
        self.assertFalse(BandMember.objects.filter(name='George Harrison').exists())

        beatles.members.commit()
        # this should create/update/delete database entries
        self.assertEqual('Ringo Starr', BandMember.objects.get(id=ringo_id).name)
        self.assertTrue(BandMember.objects.filter(name='George Harrison').exists())
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
Esempio n. 23
0
 def test_integrity_error_with_none_pk(self):
     beatles = Band(name='The Beatles', members=[
         BandMember(name='John Lennon'),
         BandMember(name='Paul McCartney'),
     ])
     beatles.save()
     beatles.pk = None
     self.assertRaises(IntegrityError, lambda: beatles.members.commit())
     # this should work fine, as Django will end up cloning this entity
     beatles.save()
     self.assertEqual(Band.objects.get(pk=beatles.pk).name, 'The Beatles')
Esempio n. 24
0
 def test_model_with_zero_pk(self):
     beatles = Band(name='The Beatles',
                    members=[
                        BandMember(name='John Lennon'),
                        BandMember(name='Paul McCartney'),
                    ])
     beatles.save()
     beatles.pk = 0
     beatles.members.commit()
     beatles.save()
     self.assertEqual(Band.objects.get(pk=0).name, 'The Beatles')
    def test_saved_items(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        first_song = Song(name='I Saw Her Standing There')
        second_song = Song(name='Misery')
        album = Album(name='Please Please Me', songs=[first_song, second_song])
        beatles = Band(name='The Beatles', albums=[album])
        beatles.save()

        self.assertTrue(album.id)
        self.assertTrue(first_song.id)
        self.assertTrue(second_song.id)

        form = BandForm({
            'name': 'The Beatles',

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 1,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': album.name,
            'albums-0-id': album.id,
            'albums-0-ORDER': 1,

            'albums-0-songs-TOTAL_FORMS': 4,
            'albums-0-songs-INITIAL_FORMS': 2,
            'albums-0-songs-MAX_NUM_FORMS': 1000,

            'albums-0-songs-0-name': first_song.name,
            'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE',
            'albums-0-songs-0-id': first_song.id,

            'albums-0-songs-1-name': second_song.name,
            'albums-0-songs-1-id': second_song.id,

            'albums-0-songs-2-name': 'Anna',
            'albums-0-songs-2-id': '',

            'albums-0-songs-3-name': '',
            'albums-0-songs-3-id': '',
        }, instance=beatles)
        self.assertTrue(form.is_valid())
        form.save()

        self.assertTrue(Song.objects.filter(name='Anna').exists())
        self.assertTrue(Song.objects.filter(name='Misery').exists())
        self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
    def test_ignore_validation_on_deleted_items(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        please_please_me = Album(name='Please Please Me', release_date=datetime.date(1963, 3, 22))
        beatles = Band(name='The Beatles', albums=[please_please_me])
        beatles.save()

        form = BandForm({
            'name': "The Beatles",

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 1,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': 'With The Beatles',
            'albums-0-release_date': '1963-02-31',  # invalid date
            'albums-0-id': please_please_me.id,
            'albums-0-ORDER': 1,
        }, instance=beatles)

        self.assertFalse(form.is_valid())

        form = BandForm({
            'name': "The Beatles",

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 1,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': 'With The Beatles',
            'albums-0-release_date': '1963-02-31',  # invalid date
            'albums-0-id': please_please_me.id,
            'albums-0-ORDER': 1,
            'albums-0-DELETE': 'albums-0-DELETE',
        }, instance=beatles)

        self.assertTrue(form.is_valid())
        form.save(commit=False)
        self.assertEqual(0, beatles.albums.count())
        self.assertEqual(1, Band.objects.get(id=beatles.id).albums.count())
        beatles.save()
        self.assertEqual(0, Band.objects.get(id=beatles.id).albums.count())
    def test_saved_items_with_non_db_relation(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        first_song = Song(name='I Saw Her Standing There')
        second_song = Song(name='Misery')
        album = Album(name='Please Please Me', songs=[first_song, second_song])
        beatles = Band(name='The Beatles', albums=[album])
        beatles.save()

        # pack and unpack the record so that we're working with a non-db-backed queryset
        new_beatles = Band.from_json(beatles.to_json())

        form = BandForm({
            'name': 'The Beatles',

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 1,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': album.name,
            'albums-0-id': album.id,
            'albums-0-ORDER': 1,

            'albums-0-songs-TOTAL_FORMS': 4,
            'albums-0-songs-INITIAL_FORMS': 2,
            'albums-0-songs-MAX_NUM_FORMS': 1000,

            'albums-0-songs-0-name': first_song.name,
            'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE',
            'albums-0-songs-0-id': first_song.id,

            'albums-0-songs-1-name': second_song.name,
            'albums-0-songs-1-id': second_song.id,

            'albums-0-songs-2-name': 'Anna',
            'albums-0-songs-2-id': '',

            'albums-0-songs-3-name': '',
            'albums-0-songs-3-id': '',
        }, instance=new_beatles)
        self.assertTrue(form.is_valid())
        form.save()

        self.assertTrue(Song.objects.filter(name='Anna').exists())
        self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
Esempio n. 28
0
    def test_saved_items_with_non_db_relation(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        first_song = Song(name='I Saw Her Standing There')
        second_song = Song(name='Misery')
        album = Album(name='Please Please Me', songs=[first_song, second_song])
        beatles = Band(name='The Beatles', albums=[album])
        beatles.save()

        # pack and unpack the record so that we're working with a non-db-backed queryset
        new_beatles = Band.from_json(beatles.to_json())

        form = BandForm({
            'name': 'The Beatles',

            'members-TOTAL_FORMS': 0,
            'members-INITIAL_FORMS': 0,
            'members-MAX_NUM_FORMS': 1000,

            'albums-TOTAL_FORMS': 1,
            'albums-INITIAL_FORMS': 1,
            'albums-MAX_NUM_FORMS': 1000,

            'albums-0-name': album.name,
            'albums-0-id': album.id,
            'albums-0-ORDER': 1,

            'albums-0-songs-TOTAL_FORMS': 4,
            'albums-0-songs-INITIAL_FORMS': 2,
            'albums-0-songs-MAX_NUM_FORMS': 1000,

            'albums-0-songs-0-name': first_song.name,
            'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE',
            'albums-0-songs-0-id': first_song.id,

            'albums-0-songs-1-name': second_song.name,
            'albums-0-songs-1-id': second_song.id,

            'albums-0-songs-2-name': 'Anna',
            'albums-0-songs-2-id': '',

            'albums-0-songs-3-name': '',
            'albums-0-songs-3-id': '',
        }, instance=new_beatles)
        self.assertTrue(form.is_valid())
        form.save()

        self.assertTrue(Song.objects.filter(name='Anna').exists())
        self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
    def test_incoming_form_data(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        beatles = Band(name='The Beatles', members=[
            BandMember(name='George Harrison'),
        ])
        form = BandForm({
            'name': "The Beatles",

            'members-TOTAL_FORMS': 4,
            'members-INITIAL_FORMS': 1,
            'members-MAX_NUM_FORMS': 1000,

            'members-0-name': 'George Harrison',
            'members-0-DELETE': 'members-0-DELETE',
            'members-0-id': '',

            'members-1-name': 'John Lennon',
            'members-1-id': '',

            'members-2-name': 'Paul McCartney',
            'members-2-id': '',

            'members-3-name': '',
            'members-3-id': '',

            'albums-TOTAL_FORMS': 0,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,
        }, instance=beatles)

        self.assertTrue(form.is_valid())
        result = form.save(commit=False)
        self.assertEqual(result, beatles)

        self.assertEqual(2, beatles.members.count())
        self.assertEqual('John Lennon', beatles.members.all()[0].name)

        # should not exist in the database yet
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())

        beatles.save()
        # this should create database entries
        self.assertTrue(Band.objects.filter(name='The Beatles').exists())
        self.assertTrue(BandMember.objects.filter(name='John Lennon').exists())
Esempio n. 30
0
    def test_incoming_form_data(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        beatles = Band(name='The Beatles', members=[
            BandMember(name='George Harrison'),
        ])
        form = BandForm({
            'name': "The Beatles",

            'members-TOTAL_FORMS': 4,
            'members-INITIAL_FORMS': 1,
            'members-MAX_NUM_FORMS': 1000,

            'members-0-name': 'George Harrison',
            'members-0-DELETE': 'members-0-DELETE',
            'members-0-id': '',

            'members-1-name': 'John Lennon',
            'members-1-id': '',

            'members-2-name': 'Paul McCartney',
            'members-2-id': '',

            'members-3-name': '',
            'members-3-id': '',

            'albums-TOTAL_FORMS': 0,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,
        }, instance=beatles)

        self.assertTrue(form.is_valid())
        result = form.save(commit=False)
        self.assertEqual(result, beatles)

        self.assertEqual(2, beatles.members.count())
        self.assertEqual('John Lennon', beatles.members.all()[0].name)

        # should not exist in the database yet
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())

        beatles.save()
        # this should create database entries
        self.assertTrue(Band.objects.filter(name='The Beatles').exists())
        self.assertTrue(BandMember.objects.filter(name='John Lennon').exists())
Esempio n. 31
0
    def test_save_commit_false(self):
        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        ringo = BandMember(name='Richard Starkey')
        beatles = Band(name='The Beatles', members=[
            john, paul, ringo
        ])
        beatles.save()

        john_id, paul_id, ringo_id = john.id, paul.id, ringo.id

        self.assertTrue(john_id)
        self.assertTrue(paul_id)

        band_members_formset = self.BandMembersFormset({
            'form-TOTAL_FORMS': 5,
            'form-INITIAL_FORMS': 3,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'John Lennon',
            'form-0-DELETE': 'form-0-DELETE',
            'form-0-id': john_id,

            'form-1-name': 'Paul McCartney',
            'form-1-id': paul_id,

            'form-2-name': 'Ringo Starr',  # changing data of an existing record
            'form-2-id': ringo_id,

            'form-3-name': '',
            'form-3-id': '',

            'form-4-name': 'George Harrison',  # Adding a record
            'form-4-id': '',
        }, queryset=beatles.members.all())
        self.assertTrue(band_members_formset.is_valid())

        updated_members = band_members_formset.save(commit=False)
        self.assertEqual(2, len(updated_members))
        self.assertEqual('Ringo Starr', updated_members[0].name)
        self.assertEqual(ringo_id, updated_members[0].id)

        # should not be updated in the db yet
        self.assertEqual('Richard Starkey', BandMember.objects.get(id=ringo_id).name)

        self.assertEqual('George Harrison', updated_members[1].name)
        self.assertFalse(updated_members[1].id)  # no ID yet
Esempio n. 32
0
    def test_save_commit_false(self):
        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        ringo = BandMember(name='Richard Starkey')
        beatles = Band(name='The Beatles', members=[
            john, paul, ringo
        ])
        beatles.save()

        john_id, paul_id, ringo_id = john.id, paul.id, ringo.id

        self.assertTrue(john_id)
        self.assertTrue(paul_id)

        band_members_formset = self.BandMembersFormset({
            'form-TOTAL_FORMS': 5,
            'form-INITIAL_FORMS': 3,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'John Lennon',
            'form-0-DELETE': 'form-0-DELETE',
            'form-0-id': john_id,

            'form-1-name': 'Paul McCartney',
            'form-1-id': paul_id,

            'form-2-name': 'Ringo Starr',  # changing data of an existing record
            'form-2-id': ringo_id,

            'form-3-name': '',
            'form-3-id': '',

            'form-4-name': 'George Harrison',  # Adding a record
            'form-4-id': '',
        }, queryset=beatles.members.all())
        self.assertTrue(band_members_formset.is_valid())

        updated_members = band_members_formset.save(commit=False)
        self.assertEqual(2, len(updated_members))
        self.assertEqual('Ringo Starr', updated_members[0].name)
        self.assertEqual(ringo_id, updated_members[0].id)

        # should not be updated in the db yet
        self.assertEqual('Richard Starkey', BandMember.objects.get(id=ringo_id).name)

        self.assertEqual('George Harrison', updated_members[1].name)
        self.assertFalse(updated_members[1].id)  # no ID yet
Esempio n. 33
0
    def test_saved_items_with_non_db_relation(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band

        beatles = Band(name='The Beatles', members=[
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ])
        beatles.save()
        member0, member1 = beatles.members.all()

        # pack and unpack the record so that we're working with a non-db-backed queryset
        new_beatles = Band.from_json(beatles.to_json())

        form = BandForm({
            'name': "The New Beatles",

            'members-TOTAL_FORMS': 4,
            'members-INITIAL_FORMS': 2,
            'members-MAX_NUM_FORMS': 1000,

            'members-0-name': member0.name,
            'members-0-DELETE': 'members-0-DELETE',
            'members-0-id': member0.id,

            'members-1-name': member1.name,
            'members-1-id': member1.id,

            'members-2-name': 'George Harrison',
            'members-2-id': '',

            'members-3-name': '',
            'members-3-id': '',

            'albums-TOTAL_FORMS': 0,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,
        }, instance=new_beatles)
        self.assertTrue(form.is_valid())
        form.save()

        new_beatles = Band.objects.get(id=beatles.id)
        self.assertEqual('The New Beatles', new_beatles.name)
        self.assertTrue(BandMember.objects.filter(name='George Harrison').exists())
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
    def test_save_commit_true(self):
        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        ringo = BandMember(name='Richard Starkey')
        beatles = Band(name='The Beatles', members=[john, paul, ringo])
        beatles.save()

        john_id, paul_id, ringo_id = john.id, paul.id, ringo.id

        self.assertTrue(john_id)
        self.assertTrue(paul_id)

        band_members_formset = self.BandMembersFormset(
            {
                'form-TOTAL_FORMS': 4,
                'form-INITIAL_FORMS': 3,
                'form-MAX_NUM_FORMS': 1000,
                'form-0-name': 'John Lennon',
                'form-0-DELETE': 'form-0-DELETE',
                'form-0-id': john_id,
                'form-1-name': 'Paul McCartney',
                'form-1-id': paul_id,
                'form-2-name':
                'Ringo Starr',  # changing data of an existing record
                'form-2-id': ringo_id,
                'form-3-name': '',
                'form-3-id': '',
            },
            queryset=beatles.members.all())
        self.assertTrue(band_members_formset.is_valid())

        updated_members = band_members_formset.save()
        self.assertEqual(1, len(updated_members))
        self.assertEqual('Ringo Starr', updated_members[0].name)
        self.assertEqual(ringo_id, updated_members[0].id)

        self.assertFalse(BandMember.objects.filter(id=john_id).exists())
        self.assertEqual('Paul McCartney',
                         BandMember.objects.get(id=paul_id).name)
        self.assertEqual(beatles.id,
                         BandMember.objects.get(id=paul_id).band_id)
        self.assertEqual('Ringo Starr',
                         BandMember.objects.get(id=ringo_id).name)
        self.assertEqual(beatles.id,
                         BandMember.objects.get(id=ringo_id).band_id)
Esempio n. 35
0
    def test_saved_items(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band

        beatles = Band(name='The Beatles', members=[
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ])
        beatles.save()
        member0, member1 = beatles.members.all()
        self.assertTrue(member0.id)
        self.assertTrue(member1.id)

        form = BandForm({
            'name': "The New Beatles",

            'members-TOTAL_FORMS': 4,
            'members-INITIAL_FORMS': 2,
            'members-MAX_NUM_FORMS': 1000,

            'members-0-name': member0.name,
            'members-0-DELETE': 'members-0-DELETE',
            'members-0-id': member0.id,

            'members-1-name': member1.name,
            'members-1-id': member1.id,

            'members-2-name': 'George Harrison',
            'members-2-id': '',

            'members-3-name': '',
            'members-3-id': '',

            'albums-TOTAL_FORMS': 0,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,
        }, instance=beatles)
        self.assertTrue(form.is_valid())
        form.save()

        new_beatles = Band.objects.get(id=beatles.id)
        self.assertEqual('The New Beatles', new_beatles.name)
        self.assertTrue(BandMember.objects.filter(name='George Harrison').exists())
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
    def test_saved_items_with_non_db_relation(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        beatles = Band(name='The Beatles', members=[john, paul])
        beatles.save()

        # pack and unpack the record so that we're working with a non-db-backed queryset
        new_beatles = Band.from_json(beatles.to_json())

        form = BandForm({
            'name': "The New Beatles",

            'members-TOTAL_FORMS': 4,
            'members-INITIAL_FORMS': 2,
            'members-MAX_NUM_FORMS': 1000,

            'members-0-name': john.name,
            'members-0-DELETE': 'members-0-DELETE',
            'members-0-id': john.id,

            'members-1-name': paul.name,
            'members-1-id': paul.id,

            'members-2-name': 'George Harrison',
            'members-2-id': '',

            'members-3-name': '',
            'members-3-id': '',

            'albums-TOTAL_FORMS': 0,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,
        }, instance=new_beatles)
        self.assertTrue(form.is_valid())
        form.save()

        new_beatles = Band.objects.get(id=beatles.id)
        self.assertEqual('The New Beatles', new_beatles.name)
        self.assertTrue(BandMember.objects.filter(name='George Harrison').exists())
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
Esempio n. 37
0
    def test_save_commit_true(self):
        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        ringo = BandMember(name='Richard Starkey')
        beatles = Band(name='The Beatles', members=[
            john, paul, ringo
        ])
        beatles.save()

        john_id, paul_id, ringo_id = john.id, paul.id, ringo.id

        self.assertTrue(john_id)
        self.assertTrue(paul_id)

        band_members_formset = self.BandMembersFormset({
            'form-TOTAL_FORMS': 4,
            'form-INITIAL_FORMS': 3,
            'form-MAX_NUM_FORMS': 1000,

            'form-0-name': 'John Lennon',
            'form-0-DELETE': 'form-0-DELETE',
            'form-0-id': john_id,

            'form-1-name': 'Paul McCartney',
            'form-1-id': paul_id,

            'form-2-name': 'Ringo Starr',  # changing data of an existing record
            'form-2-id': ringo_id,

            'form-3-name': '',
            'form-3-id': '',
        }, queryset=beatles.members.all())
        self.assertTrue(band_members_formset.is_valid())

        updated_members = band_members_formset.save()
        self.assertEqual(1, len(updated_members))
        self.assertEqual('Ringo Starr', updated_members[0].name)
        self.assertEqual(ringo_id, updated_members[0].id)

        self.assertFalse(BandMember.objects.filter(id=john_id).exists())
        self.assertEqual('Paul McCartney', BandMember.objects.get(id=paul_id).name)
        self.assertEqual(beatles.id, BandMember.objects.get(id=paul_id).band_id)
        self.assertEqual('Ringo Starr', BandMember.objects.get(id=ringo_id).name)
        self.assertEqual(beatles.id, BandMember.objects.get(id=ringo_id).band_id)
    def test_saved_items(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        beatles = Band(name='The Beatles', members=[john, paul])
        beatles.save()
        self.assertTrue(john.id)
        self.assertTrue(paul.id)

        form = BandForm({
            'name': "The New Beatles",

            'members-TOTAL_FORMS': 4,
            'members-INITIAL_FORMS': 2,
            'members-MAX_NUM_FORMS': 1000,

            'members-0-name': john.name,
            'members-0-DELETE': 'members-0-DELETE',
            'members-0-id': john.id,

            'members-1-name': paul.name,
            'members-1-id': paul.id,

            'members-2-name': 'George Harrison',
            'members-2-id': '',

            'members-3-name': '',
            'members-3-id': '',

            'albums-TOTAL_FORMS': 0,
            'albums-INITIAL_FORMS': 0,
            'albums-MAX_NUM_FORMS': 1000,
        }, instance=beatles)
        self.assertTrue(form.is_valid())
        form.save()

        new_beatles = Band.objects.get(id=beatles.id)
        self.assertEqual('The New Beatles', new_beatles.name)
        self.assertTrue(BandMember.objects.filter(name='George Harrison').exists())
        self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
    def test_can_omit_formset_from_submission(self):
        """
        If no explicit `formsets` parameter has been given, any formsets missing from the
        submission should be skipped over.
        https://github.com/wagtail/wagtail/issues/5414#issuecomment-567468127
        """
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']

        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        abbey_road = Album(name='Abbey Road')
        beatles = Band(name='The Beatles',
                       members=[john, paul],
                       albums=[abbey_road])
        beatles.save()

        form = BandForm(
            {
                'name': "The Beatles",
                'members-TOTAL_FORMS': 3,
                'members-INITIAL_FORMS': 2,
                'members-MAX_NUM_FORMS': 1000,
                'members-0-name': john.name,
                'members-0-DELETE': 'members-0-DELETE',
                'members-0-id': john.id,
                'members-1-name': paul.name,
                'members-1-id': paul.id,
                'members-2-name': 'George Harrison',
                'members-2-id': '',
            },
            instance=beatles)
        self.assertTrue(form.is_valid())
        form.save()

        beatles = Band.objects.get(id=beatles.id)
        self.assertEqual(1, beatles.albums.count())
        self.assertTrue(
            BandMember.objects.filter(name='George Harrison').exists())
        self.assertFalse(
            BandMember.objects.filter(name='John Lennon').exists())
    def test_commit(self):
        # The commit parameter will instruct the method to save the child objects straight away

        self.beatles.save()
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')
        album_1 = self.beatles.albums.get(sort_order=1)
        album_2 = self.beatles.albums.get(sort_order=2)
        album_3 = self.beatles.albums.get(sort_order=3)

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.save()

        child_object_mapping = self.beatles.copy_all_child_relations(
            beatles_clone, commit=True)

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        new_album_1 = beatles_clone.albums.get(sort_order=1)
        new_album_2 = beatles_clone.albums.get(sort_order=2)
        new_album_3 = beatles_clone.albums.get(sort_order=3)

        self.assertIsNotNone(new_john.pk)
        self.assertIsNotNone(new_paul.pk)
        self.assertIsNotNone(new_album_1.pk)
        self.assertIsNotNone(new_album_2.pk)
        self.assertIsNotNone(new_album_3.pk)

        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)
        self.assertEqual(new_album_1.band, beatles_clone)
        self.assertEqual(new_album_2.band, beatles_clone)
        self.assertEqual(new_album_3.band, beatles_clone)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, john.pk): new_john,
                (band_members_rel, paul.pk): new_paul,
                (band_albums_rel, album_1.pk): new_album_1,
                (band_albums_rel, album_2.pk): new_album_2,
                (band_albums_rel, album_3.pk): new_album_3,
            })
Esempio n. 41
0
    def test_cluster_form_without_formsets(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                formsets = ()

        beatles = Band(name='The Beatles')
        beatles.save()

        form = BandForm({
            'name': "The New Beatles",
        }, instance=beatles)

        self.assertTrue(form.is_valid())

        form.save(commit=False)

        self.assertEqual(1, Band.objects.filter(name='The Beatles').count())
        beatles.save()
        self.assertEqual(0, Band.objects.filter(name='The Beatles').count())
    def test_overwrites_existing_child_relations(self):
        # By default, the copy_child_relations should overwrite existing items
        # This is the safest option as there could be unique keys or sort_order
        # fields that might not like being duplicated in this way.

        self.beatles.save()
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.members.add(BandMember(name='Julian Lennon'))
        beatles_clone.save()

        self.assertTrue(
            beatles_clone.members.filter(name='Julian Lennon').exists())

        self.beatles.copy_child_relation('members', beatles_clone)

        self.assertFalse(
            beatles_clone.members.filter(name='Julian Lennon').exists())
    def test_cluster_form_without_formsets(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                formsets = ()
                fields = ['name']

        beatles = Band(name='The Beatles')
        beatles.save()

        form = BandForm({
            'name': "The New Beatles",
        }, instance=beatles)

        self.assertTrue(form.is_valid())

        form.save(commit=False)

        self.assertEqual(1, Band.objects.filter(name='The Beatles').count())
        beatles.save()
        self.assertEqual(0, Band.objects.filter(name='The Beatles').count())
Esempio n. 44
0
    def test_save_with_update_fields(self):
        beatles = Band(name='The Beatles', members=[
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ], albums=[
            Album(name='Please Please Me', sort_order=1),
            Album(name='With The Beatles', sort_order=2),
            Album(name='Abbey Road', sort_order=3),
        ])

        beatles.save()

        # modify both relations, but only commit the change to members
        beatles.members.clear()
        beatles.albums.clear()
        beatles.name = 'The Rutles'
        beatles.save(update_fields=['name', 'members'])

        updated_beatles = Band.objects.get(pk=beatles.pk)
        self.assertEqual(updated_beatles.name, 'The Rutles')
        self.assertEqual(updated_beatles.members.count(), 0)
        self.assertEqual(updated_beatles.albums.count(), 3)
    def test_save_with_update_fields(self):
        beatles = Band(name='The Beatles', members=[
            BandMember(name='John Lennon'),
            BandMember(name='Paul McCartney'),
        ], albums=[
            Album(name='Please Please Me', sort_order=1),
            Album(name='With The Beatles', sort_order=2),
            Album(name='Abbey Road', sort_order=3),
        ])

        beatles.save()

        # modify both relations, but only commit the change to members
        beatles.members.clear()
        beatles.albums.clear()
        beatles.name = 'The Rutles'
        beatles.save(update_fields=['name', 'members'])

        updated_beatles = Band.objects.get(pk=beatles.pk)
        self.assertEqual(updated_beatles.name, 'The Rutles')
        self.assertEqual(updated_beatles.members.count(), 0)
        self.assertEqual(updated_beatles.albums.count(), 3)
    def test_queryset_filtering(self):
        beatles = Band(name='The Beatles', members=[
            BandMember(id=1, name='John Lennon'),
            BandMember(id=2, name='Paul McCartney'),
        ])
        self.assertEqual('Paul McCartney', beatles.members.get(id=2).name)
        self.assertEqual('Paul McCartney', beatles.members.get(id='2').name)
        self.assertEqual(1, beatles.members.filter(name='Paul McCartney').count())

        # also need to be able to filter on foreign fields that return a model instance
        # rather than a simple python value
        self.assertEqual(2, beatles.members.filter(band=beatles).count())
        # and ensure that the comparison is not treating all unsaved instances as identical
        rutles = Band(name='The Rutles')
        self.assertEqual(0, beatles.members.filter(band=rutles).count())

        # and the comparison must be on the model instance's ID where available,
        # not by reference
        beatles.save()
        beatles.members.add(BandMember(id=3, name='George Harrison'))  # modify the relation so that we're not to a plain database-backed queryset

        also_beatles = Band.objects.get(id=beatles.id)
        self.assertEqual(3, beatles.members.filter(band=also_beatles).count())
Esempio n. 47
0
    def test_cannot_omit_explicit_formset_from_submission(self):
        """
        If an explicit `formsets` parameter has been given, formsets missing from a form submission
        should raise a ValidationError as normal
        """
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                fields = ['name']
                formsets = ['members', 'albums']

        john = BandMember(name='John Lennon')
        paul = BandMember(name='Paul McCartney')
        abbey_road = Album(name='Abbey Road')
        beatles = Band(name='The Beatles', members=[john, paul], albums=[abbey_road])
        beatles.save()

        form = BandForm({
            'name': "The Beatles",

            'members-TOTAL_FORMS': 3,
            'members-INITIAL_FORMS': 2,
            'members-MAX_NUM_FORMS': 1000,

            'members-0-name': john.name,
            'members-0-DELETE': 'members-0-DELETE',
            'members-0-id': john.id,

            'members-1-name': paul.name,
            'members-1-id': paul.id,

            'members-2-name': 'George Harrison',
            'members-2-id': '',
        }, instance=beatles)

        with self.assertRaises(ValidationError):
            form.is_valid()
class TestCopyAllChildRelations(TestCase):
    def setUp(self):
        self.beatles = Band(name='The Beatles',
                            members=[
                                BandMember(name='John Lennon'),
                                BandMember(name='Paul McCartney'),
                            ],
                            albums=[
                                Album(name='Please Please Me', sort_order=1),
                                Album(name='With The Beatles', sort_order=2),
                                Album(name='Abbey Road', sort_order=3),
                            ])

    def test_copy_all_child_relations_unsaved(self):
        # Let's imagine that cloned bands own the albums of their source
        # (I'm not creative enough to come up with new album names to keep this analogy going...)

        beatles_clone = Band(name='The Beatles 2020 comeback')
        child_object_mapping = self.beatles.copy_all_child_relations(
            beatles_clone)

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        new_album_1 = beatles_clone.albums.get(sort_order=1)
        new_album_2 = beatles_clone.albums.get(sort_order=2)
        new_album_3 = beatles_clone.albums.get(sort_order=3)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, None): [new_john, new_paul],
                (band_albums_rel, None):
                [new_album_1, new_album_2, new_album_3],
            })

    def test_copy_all_child_relations_saved(self):
        self.beatles.save()

        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')
        album_1 = self.beatles.albums.get(sort_order=1)
        album_2 = self.beatles.albums.get(sort_order=2)
        album_3 = self.beatles.albums.get(sort_order=3)

        beatles_clone = Band(name='The Beatles 2020 comeback')
        child_object_mapping = self.beatles.copy_all_child_relations(
            beatles_clone)

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        new_album_1 = beatles_clone.albums.get(sort_order=1)
        new_album_2 = beatles_clone.albums.get(sort_order=2)
        new_album_3 = beatles_clone.albums.get(sort_order=3)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, john.pk): new_john,
                (band_members_rel, paul.pk): new_paul,
                (band_albums_rel, album_1.pk): new_album_1,
                (band_albums_rel, album_2.pk): new_album_2,
                (band_albums_rel, album_3.pk): new_album_3,
            })

    def test_exclude(self):
        beatles_clone = Band(name='The Beatles 2020 comeback')
        child_object_mapping = self.beatles.copy_all_child_relations(
            beatles_clone, exclude=['albums'])

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        self.assertFalse(beatles_clone.albums.exists())

        self.assertEqual(child_object_mapping, {
            (band_members_rel, None): [new_john, new_paul],
        })

    def test_overwrites_existing_child_relations(self):
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.members.add(BandMember(name='Julian Lennon'))

        self.assertTrue(
            beatles_clone.members.filter(name='Julian Lennon').exists())

        child_object_mapping = self.beatles.copy_all_child_relations(
            beatles_clone)

        self.assertFalse(
            beatles_clone.members.filter(name='Julian Lennon').exists())

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        new_album_1 = beatles_clone.albums.get(sort_order=1)
        new_album_2 = beatles_clone.albums.get(sort_order=2)
        new_album_3 = beatles_clone.albums.get(sort_order=3)

        self.assertIsNone(new_john.pk)
        self.assertIsNone(new_paul.pk)
        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, None): [new_john, new_paul],
                (band_albums_rel, None):
                [new_album_1, new_album_2, new_album_3],
            })

    def test_commit(self):
        # The commit parameter will instruct the method to save the child objects straight away

        self.beatles.save()
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')
        album_1 = self.beatles.albums.get(sort_order=1)
        album_2 = self.beatles.albums.get(sort_order=2)
        album_3 = self.beatles.albums.get(sort_order=3)

        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.save()

        child_object_mapping = self.beatles.copy_all_child_relations(
            beatles_clone, commit=True)

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')

        new_album_1 = beatles_clone.albums.get(sort_order=1)
        new_album_2 = beatles_clone.albums.get(sort_order=2)
        new_album_3 = beatles_clone.albums.get(sort_order=3)

        self.assertIsNotNone(new_john.pk)
        self.assertIsNotNone(new_paul.pk)
        self.assertIsNotNone(new_album_1.pk)
        self.assertIsNotNone(new_album_2.pk)
        self.assertIsNotNone(new_album_3.pk)

        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)
        self.assertEqual(new_album_1.band, beatles_clone)
        self.assertEqual(new_album_2.band, beatles_clone)
        self.assertEqual(new_album_3.band, beatles_clone)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, john.pk): new_john,
                (band_members_rel, paul.pk): new_paul,
                (band_albums_rel, album_1.pk): new_album_1,
                (band_albums_rel, album_2.pk): new_album_2,
                (band_albums_rel, album_3.pk): new_album_3,
            })

    def test_commit_to_unsaved(self):
        # You can't use commit if the target isn't saved
        self.beatles.save()
        john = self.beatles.members.get(name='John Lennon')
        paul = self.beatles.members.get(name='Paul McCartney')

        beatles_clone = Band(name='The Beatles 2020 comeback')

        with self.assertRaises(IntegrityError):
            self.beatles.copy_all_child_relations(beatles_clone, commit=True)

    def test_append(self):
        beatles_clone = Band(name='The Beatles 2020 comeback')
        beatles_clone.members.add(BandMember(name='Julian Lennon'))

        self.assertTrue(
            beatles_clone.members.filter(name='Julian Lennon').exists())

        child_object_mapping = self.beatles.copy_all_child_relations(
            beatles_clone, append=True)

        self.assertTrue(
            beatles_clone.members.filter(name='Julian Lennon').exists())

        new_john = beatles_clone.members.get(name='John Lennon')
        new_paul = beatles_clone.members.get(name='Paul McCartney')
        new_album_1 = beatles_clone.albums.get(sort_order=1)
        new_album_2 = beatles_clone.albums.get(sort_order=2)
        new_album_3 = beatles_clone.albums.get(sort_order=3)

        self.assertIsNone(new_john.pk)
        self.assertIsNone(new_paul.pk)
        self.assertEqual(new_john.band, beatles_clone)
        self.assertEqual(new_paul.band, beatles_clone)

        self.assertEqual(
            child_object_mapping, {
                (band_members_rel, None): [new_john, new_paul],
                (band_albums_rel, None):
                [new_album_1, new_album_2, new_album_3],
            })