Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

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.

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:

PYTHON
from 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:

PYTHON
class 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:

PYTHON
class 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?

0

Comments 0

Answers 0

Views 147

0 Answers

Discussion

No comments yet.