| | 1830 | <option value="J">Java</option> |
|---|
| | 1831 | </select> |
|---|
| | 1832 | |
|---|
| | 1833 | You can specify widget attributes in the Widget constructor. |
|---|
| | 1834 | >>> class FrameworkForm(Form): |
|---|
| | 1835 | ... name = CharField() |
|---|
| | 1836 | ... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'})) |
|---|
| | 1837 | >>> f = FrameworkForm(auto_id=False) |
|---|
| | 1838 | >>> print f['language'] |
|---|
| | 1839 | <select class="foo" name="language"> |
|---|
| | 1840 | <option value="P">Python</option> |
|---|
| | 1841 | <option value="J">Java</option> |
|---|
| | 1842 | </select> |
|---|
| | 1843 | >>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) |
|---|
| | 1844 | >>> print f['language'] |
|---|
| | 1845 | <select class="foo" name="language"> |
|---|
| | 1846 | <option value="P" selected="selected">Python</option> |
|---|
| | 1847 | <option value="J">Java</option> |
|---|
| | 1848 | </select> |
|---|
| | 1849 | |
|---|
| | 1850 | When passing a custom widget instance to ChoiceField, note that setting |
|---|
| | 1851 | 'choices' on the widget is meaningless. The widget will use the choices |
|---|
| | 1852 | defined on the Field, not the ones defined on the Widget. |
|---|
| | 1853 | >>> class FrameworkForm(Form): |
|---|
| | 1854 | ... name = CharField() |
|---|
| | 1855 | ... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'})) |
|---|
| | 1856 | >>> f = FrameworkForm(auto_id=False) |
|---|
| | 1857 | >>> print f['language'] |
|---|
| | 1858 | <select class="foo" name="language"> |
|---|
| | 1859 | <option value="P">Python</option> |
|---|
| | 1860 | <option value="J">Java</option> |
|---|
| | 1861 | </select> |
|---|
| | 1862 | >>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) |
|---|
| | 1863 | >>> print f['language'] |
|---|
| | 1864 | <select class="foo" name="language"> |
|---|
| | 1865 | <option value="P" selected="selected">Python</option> |
|---|
| | 1866 | <option value="J">Java</option> |
|---|
| | 1867 | </select> |
|---|
| | 1868 | |
|---|
| | 1869 | You can set a ChoiceField's choices after the fact. |
|---|
| | 1870 | >>> class FrameworkForm(Form): |
|---|
| | 1871 | ... name = CharField() |
|---|
| | 1872 | ... language = ChoiceField() |
|---|
| | 1873 | >>> f = FrameworkForm(auto_id=False) |
|---|
| | 1874 | >>> print f['language'] |
|---|
| | 1875 | <select name="language"> |
|---|
| | 1876 | </select> |
|---|
| | 1877 | >>> f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] |
|---|
| | 1878 | >>> print f['language'] |
|---|
| | 1879 | <select name="language"> |
|---|
| | 1880 | <option value="P">Python</option> |
|---|