How to add attributes to option tags in django ?

后端 未结 6 2000
闹比i
闹比i 2020-12-14 11:01

I have to add title attribute to options of the ModelChoiceField. Here is my admin code for that:

class LocModelForm(forms.ModelForm):
        def __init__(s         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 11:21

    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-rendering

    Here 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:

    class MyForm(forms.ModelForm):
        project = ProjectModelChoiceField(label=_('Project'), widget=ProjectSelect())
    

    Then I declare the classes from above and one extra, the iterator:

    class ProjectModelChoiceIterator(django.forms.models.ModelChoiceIterator):
        def choice(self, obj):
            # return (self.field.prepare_value(obj), self.field.label_from_instance(obj)) #it used to be like this, but we need the extra context from the object not just the label. 
            return (self.field.prepare_value(obj), obj)
    
    class ProjectModelChoiceField(django.forms.models.ModelChoiceField):
       def _get_choices(self):
           if hasattr(self, '_choices'):
               return self._choices
           return ProjectModelChoiceIterator(self)
    
    
    class ProjectSelect(django.forms.Select):
    
        def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
            context = super(ProjectSelect, self).create_option(name, value, label, selected, index, subindex=None, attrs=None)
    
            context['attrs']['extra-attribute'] = label.extra_attribute #label is now an object, not just a string.
            return context
    

提交回复
热议问题