创建一个使用两个<input />的自定义Django表单字段

时间:2010-03-05 12:11:25

标签: python django django-forms

如何创建一个将自身呈现为一对输入的Django字段 字段?

推理:我正在尝试编写一个新的自定义字段。我会用它来做一个 类似验证码的服务。该服务通过提出问题来工作 - 然后接收一个和令牌。通过发送验证来进行验证 回答以及令牌。我想写一个表单字段 封装了这个逻辑。元素应该呈现(IMO)像

<input type="hidden" name="_token" value="1234567890" />
<input type="text" name="answer" />

在提交时,我需要_tokenanswer的值来验证答案。

3 个答案:

答案 0 :(得分:9)

我认为你正在寻找MultiWidget,你可以简单地给它2个常规小工具,它会渲染组合。

答案 1 :(得分:4)

这里有一个现成的例子(取自我的博客):

class ComplexMultiWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        widgets = (
            forms.TextInput(),
            forms.SelectMultiple(choices=(('J', 'John'),
                                          ('P', 'Paul'),
                                          ('G', 'George'),
                                          ('R', 'Ringo'))),
            forms.SplitDateTimeWidget(),
        )
        super(ComplexMultiWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            data = value.split(',')
            return [data[0], data[1],
                   datetime.datetime(*time.strptime(data[2],
                   "%Y-%m-%d %H:%M:%S")[0:6])]
        return [None, None, None]
    def format_output(self, rendered_widgets):
        return u'\n'.join(rendered_widgets)


class ComplexField(forms.MultiValueField):
    def __init__(self, required=True, widget=None, label=None, initial=None):
        fields = (
            forms.CharField(),
            forms.MultipleChoiceField(choices=(('J', 'John'),
                                               ('P', 'Paul'),
                                               ('G', 'George'),
                                               ('R', 'Ringo'))),
            forms.SplitDateTimeField()
        )
        super(ComplexField, self).__init__(fields, required,
                                           widget, label, initial)

    def compress(self, data_list):
        if data_list:
            return '%s,%s,%s' % (data_list[0],''.join(data_list[1]),
                                 data_list[2])
        return None

示例使用方法:

>>> f = ComplexField(widget=ComplexMultiWidget())
>>> f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']])
u'some text,JP,2007-04-25 06:24:00'
>>> f.clean(['some text',['X'], ['2007-04-25','6:24:00']])
Traceback (most recent call last):
...
ValidationError: [u'Select a valid choice. X is not one of the available choices.']

>>> f.clean(['some text',['JP']])
Traceback (most recent call last):

>>> class ComplexFieldForm(Form):
            field1 = ComplexField(widget=ComplexMultiWidget())

>>> f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'})
>>> print f
<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" value="some text" id="id_field1_0" />
<select multiple="multiple" name="field1_1" id="id_field1_1">
<option value="J" selected="selected">John</option>
<option value="P" selected="selected">Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>
<input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" /><input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" /></td></tr>

>>> f.cleaned_data
{'field1': u'some text,JP,2007-04-25 06:24:00'}

答案 2 :(得分:2)

查看SelectDateWidget。它将日期输入拆分为三个选择框。

文档字符串说:

  

这也是一个Widget的例子,它有多个HTML元素,因此实现了value_from_datadict