How to set title and class in the HTML for the options of a ModelChoiceField?
- by celopes
I have a model
class MyModel(models.Model):
name = models.CharField(max_length=80, unique=True)
parent = models.ForeignKey('self', null=True, blank=True)
I want to render a ModelChoiceField for that model that looks like:
<select name="mymodel" id="id_mymodel">
<option value="1" title="Value 1" class="">Value 1</option>
<option value="2" title="Value 2" class="Value 1">Value 2</option>
</select>
The differences between this output and the default output for a ModelChoiceField are the title and class elements in the OPTION tag. They don't exist in ModelChoiceField's default output.
For my purposes:
The title element is supposed to be the Option Name.
The class element is supposed to be self.parent.name. (this is my problem)
So, in the HTML snippet above, Value 1 has no parent and Value 2 has a parent of Value 1.
What is the best mechanism to change ModelChoiceField's default HTML output?
EDIT: I understand how to create a new Widget for rendering HTML. The problem is how to render a value from the underlying model in each of the options.