A callable can be provided as the initial value for an m2m field.
(self)
| 1625 | self.assertEqual(test_art.headline, "Test headline") |
| 1626 | |
| 1627 | def test_m2m_initial_callable(self): |
| 1628 | """ |
| 1629 | A callable can be provided as the initial value for an m2m field. |
| 1630 | """ |
| 1631 | self.maxDiff = 1200 |
| 1632 | self.create_basic_data() |
| 1633 | |
| 1634 | # Set up a callable initial value |
| 1635 | def formfield_for_dbfield(db_field, **kwargs): |
| 1636 | if db_field.name == "categories": |
| 1637 | kwargs["initial"] = lambda: Category.objects.order_by("name")[:2] |
| 1638 | return db_field.formfield(**kwargs) |
| 1639 | |
| 1640 | # Create a ModelForm, instantiate it, and check that the output is as |
| 1641 | # expected |
| 1642 | ModelForm = modelform_factory( |
| 1643 | Article, |
| 1644 | fields=["headline", "categories"], |
| 1645 | formfield_callback=formfield_for_dbfield, |
| 1646 | ) |
| 1647 | form = ModelForm() |
| 1648 | self.assertHTMLEqual( |
| 1649 | form.as_ul(), |
| 1650 | """<li><label for="id_headline">Headline:</label> |
| 1651 | <input id="id_headline" type="text" name="headline" maxlength="50" required></li> |
| 1652 | <li><label for="id_categories">Categories:</label> |
| 1653 | <select multiple name="categories" id="id_categories"> |
| 1654 | <option value="%s" selected>Entertainment</option> |
| 1655 | <option value="%s" selected>It's a test</option> |
| 1656 | <option value="%s">Third test</option> |
| 1657 | </select></li>""" % (self.c1.pk, self.c2.pk, self.c3.pk), |
| 1658 | ) |
| 1659 | |
| 1660 | def test_basic_creation(self): |
| 1661 | self.assertEqual(Category.objects.count(), 0) |
nothing calls this directly
no test coverage detected