MCPcopy
hub / github.com/django/django / test_m2m_initial_callable

Method test_m2m_initial_callable

tests/model_forms/tests.py:1627–1658  ·  view source on GitHub ↗

A callable can be provided as the initial value for an m2m field.

(self)

Source from the content-addressed store, hash-verified

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&#x27;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)

Callers

nothing calls this directly

Calls 5

create_basic_dataMethod · 0.95
modelform_factoryFunction · 0.90
assertHTMLEqualMethod · 0.80
ModelFormClass · 0.70
as_ulMethod · 0.45

Tested by

no test coverage detected