Asked 2 months ago by CosmicScholar593
How can I dynamically add custom attributes to Django ModelChoiceField options?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 2 months ago by CosmicScholar593
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I’m trying to add a transient attribute (like a status indicator) to each option of a Django ModelChoiceField so I can use JavaScript to hide or show elements based on checkbox changes. The custom attribute is generated at each page load, and I’m extending the widget’s create_option method to inject this attribute. However, while the Python logs confirm that the attribute is being added, the final rendered HTML does not include it.
Below is the original code I adapted from the Django docs and other online solutions:
PYTHONfrom django import forms class ToppingSelect(forms.Select): def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): option = super().create_option( name, value, label, selected, index, subindex, attrs ) if value: option["attrs"]["data-price"] = value.instance.price return option class PizzaForm(forms.ModelForm): class Meta: model = Pizza fields = ["topping"] widgets = {"topping": ToppingSelect}
I then implemented my custom select as follows:
PYTHONclass CustomSelectWithAttrs(forms.Select): def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): option = super().create_option( name, value, label, selected, index, subindex, attrs ) print(f'option = {option}') print(f'\tattrs = {attrs}') print(f'\tvalue = {value} instance={value.instance}') if value: print(f'\tstatus = {value.instance.status}') option["attrs"]['current-status'] = value.instance.status.state print(f'all set now: option = {option}') return option
And here is the form using the custom widget:
PYTHONclass MatchFilterForm(ModelForm): class Meta: model = Match fields = {'tutor', 'student', 'match_status', 'date_started', 'comments'} exclude = {'lvm_affiliate', 'date_dissolved', } labels = {'tutor': 'Tutor pool', 'student': 'Student pool', 'match_status': "Status", 'date_started': "Start date", 'comments': 'Comments'} widgets = { 'date_started': DateInput( format='%Y-%m-%d', attrs={ 'class': 'form-control', 'placeholder': 'Select a date', 'type': 'date' } ), 'student': CustomSelectWithAttrs, }
The form renders correctly, but the custom attribute (‘current-status’) does not appear in the final HTML output. Has anyone encountered this behavior or know what might be interfering with the attribute rendering in the widget's create_option method?
Comments 0
•Answers 0
•Views 147
No comments yet.