Django forms give the ability to override the create_option() function for custom Select fields.
You can use this to set custom attributes for each select option.
The function is triggered when the form is called in the template. So if we have {{ form.custom_select_field }} in the html file, create_option is called when the file is rendered. This works fine with the above syntax, but when using {{ form.field|as_crispy_field }} the create_option no longer executes. (Note: though I verified that the CustomSelect's __init__ method was still being called.
The functionality
Django forms give the ability to override the
create_option()
function for custom Select fields.You can use this to set custom attributes for each select option.
The function is triggered when the form is called in the template. So if we have
{{ form.custom_select_field }}
in the html file,create_option
is called when the file is rendered. This works fine with the above syntax, but when using{{ form.field|as_crispy_field }}
thecreate_option
no longer executes. (Note: though I verified that theCustomSelect
's__init__
method was still being called.Source code
requirements.txt
forms.py
form.html
Notes
All the form fields render fine with the styling, but the custom select widget only works for
{{ form.state }}
without theas_crispy_field
.I put a print statement in
RegionSelect.create_option()
and confirmed that it never even executes when we use crispy.This behavior is also true with
{{ form }}
working as expected, but{{ form|crispy }}
causingRegionSelect.create_option()
to not execute.