I have to add title attribute to options of the ModelChoiceField. Here is my admin code for that:
class LocModelForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(LocModelForm,self).__init__(*args,**kwargs)
self.fields['icons'] = forms.ModelChoiceField(queryset = Photo.objects.filter(galleries__title_slug = "markers"))
self.fields['icons'].widget.attrs['class'] = 'mydds'
class Meta:
model = Loc
widgets = {
'icons' : forms.Select(attrs={'id':'mydds'}),
}
class Media:
css = {
"all":("/media/css/dd.css",)
}
js=(
'/media/js/dd.js',
)
class LocAdmin(admin.ModelAdmin):
form = LocModelForm
I can add any attribute to select widget, but i don't know how to add attributes to option tags. Any idea ?
I had a similar problem, where I needed to add a custom attribute to each option dynamically. But in Django 2.0, the html rendering was moved into the Widget base class, so modifying
render_option
no longer works. Here is the solution that worked for me:Then in views, render a context with
{'form': CustomForm(choices=choices, src=src)}
wheresrc
is a dictionary like this:{'attr-name': {'option_value': 'attr_value'}}
.Here's a class I made that inherits from forms.Select (thanks to Cat Plus Plus for getting me started with this). On initialization, provide the option_title_field parameter indicating which field to use for the
<option>
title attribute.From django 1.11 and above the
render_option
method was removed. see this link: https://docs.djangoproject.com/en/1.11/releases/1.11/#changes-due-to-the-introduction-of-template-based-widget-renderingHere is a solution that worked for me different than Kayoz's. I did not adapt the names as in the example but i hope it is still clear. In the model form I overwrite the field:
Then I declare the classes from above and one extra, the iterator:
First of all, don't modify fields in
__init__
, if you want to override widgets useMeta
inner class, if you want to override form fields, declare them like in a normal (non-model) form.If the
Select
widget does not do what you want, then simply make your own. Original widget usesrender_option
method to get HTML representation for a single option — make a subclass, override it, and add whatever you want.