So let's say I have jQuery convert a simple text input from this
<input class='employee_list' name='requestor' type='text' />
to this
<div name='requestor' class='ajax_picker'>
<input class='search_box' class='employee_list' name='requestor_text' type='text'/>
<input class='id' name='requestor' type='hidden' value='' />
<div class='results'></div>
</div>
And load the hidden input value with AJAX + JSON. Problem is, if form.is_valid() is not True
, then how can I create a custom Widget that will render both values? Thinking I could do two different fields, but that seems ugly. I could also customize the form rendering, but that's even worse. Maybe the form can pass all of the POST data to the widget, but can't seem to figure out how to get that to work.
There must be an elegant way to achieve this!
from django import forms
class AjaxPickerWidget(forms.TextInput):
def render(self, name, value, attrs=None):
# ... now what?
return super(AjaxPickerWidget, self).render(name, value, attrs=attrs)
My Solution
Thanks for your help, I took a variant approach. Since I am using this strictly for Models (hence needing a key/value pair) I made the widget interact directly with the model and create a data-id
attribute that the jQuery would catch to move to the hidden field.
from django import forms
class AjaxPickerModelWidget(forms.TextInput):
def __init__(self, css_class, queryset, id_name, value_name, attrs={}):
attrs['class'] = css_class
self.queryset = queryset
self.id_name = id_name
self.value_name = value_name
super(AjaxPickerModelWidget, self).__init__(attrs=attrs)
def render(self, name, value, attrs={}):
try:
instance = self.queryset.get(**{self.id_name: value})
attrs['data-id'] = value
value = getattr(instance, self.value_name)
except:
value = ''
return super(AjaxPickerModelWidget, self).render(name, value,
attrs=attrs)