0

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)
4

2 回答 2

1

好吧,我不知道这是否称得上优雅,但是像这样的东西怎么样。在这里,我将搜索字符串作为属性存储在小部件上,并从表单构造函数中的 POST 数据设置属性。我还使用 name="foo_picker_text" 来指示名为“foo”的相应输入的搜索输入。

class AjaxPickerWidget(HiddenInput):
  search_text_suffix = "_picker_text"

  def __init__(self, **kwargs):
    super(AjaxPickerWidget, self).__init__(**kwargs)
    self.search_text = None

  def render(self, name, value, attrs=None):
    start = '<div name="%s" class="ajax_picker">' % (name) + \
             '<input class="search_box" name="%s%s" ' % (name, self.search_text_suffix)+ \
             'type="text" value="%s" />' % (self.search_text or "")
    end = super(AjaxPickerWidget, self).render(name, value, attrs=attrs) + '</div>'
    return '%s%s' % (start, end)

class MyForm(Form):
  requestor = CharField(widget = AjaxPickerWidget())

  def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    # find picker text in POST data and tell the corresponding widget about it
    for name in self.data:
      if name.endswith(AjaxPickerWidget.search_text_suffix):
        field_name = name.split(AjaxPickerWidget.search_text_suffix)[0]
        self.fields[field_name].widget.search_text = self.data[name]

您可能需要对其进行一些调整以使属性显示在您想要的位置等,但希望这基本上可以满足您的需求?

于 2012-12-09T23:53:56.993 回答
0

您可以代替调用is_valid()表单创建自定义函数

from django import forms

class AjaxPickerWidget(forms.TextInput):
    def render(self, name, value, attrs=None):
        return super(AjaxPickerWidget, self).render(name, value, attrs=attrs)
    def validate(self):
        values = self.cleaned_data.items():
        # Modify the values to fit the original form (delete, change etc)
        return whateversleft.is_valid() # Perhaps with some additional checks
于 2012-12-10T12:18:40.740 回答