I'm writing a custom Form widget that overrides the choice
method in django.forms.models.ModelChoiceIterator
:
class CustomIterator(ModelChoiceIterator):
def choice(self, obj):
return (self.field.prepare_value(obj),
self.field.label_from_instance(obj), obj)
As well as the _get_choices
method on django.forms.models.ModelChoiceField
:
class CustomField(ModelChoiceField):
def _get_choices(self):
if hasattr(self, '_choices'):
return self._choices
return ElfIterator(self)
choices = property(_get_choices, ChoiceField._set_choices)
(I followed the example on this blog post)
I need to create a totally custom widget that selects objects based on, say, the value of the data-selected
attribute on an HTML element. I've been able to get the custom HTML/styling to be displayed on the form using the instance attributes added by the above:
from django.template.loader import render_to_string
class CustomWidget(Widget):
def render(self, name, value, attrs=None):
obj_list = [item[2] for item in self.choices]
obj_dict = [model_to_dict(obj) for obj in obj_list]
output = render_to_string('myapp/widgets/custom_widget.html',
{ 'obj_dict': obj_dict })
return mark_safe(output)
Now I'm attempting to override the value_from_datadict
method on this same class, however it's not clear to me, even from reading the source code, how I'd be able to return the selected value based on an arbitrary HTML attribute without a Select widget.