views:

239

answers:

3

How can I make a Django field that renders itself as a pair of input fields?

Reasoning: I am trying to write a new custom field. I will use it for a captcha-like service. The service works by requesting a question - then receiving one and a token. The validation happens by sending the answer along with the token. I want to write a form field that encapsulates this logic. The elements should render (IMO) like

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

And on submit I need the value of _token and answer to validate the answer.

+1  A: 

Have a look at the SelectDateWidget. It splits the input of a date into three select boxes.

And the doc string says:

This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict.

Felix Kling
+6  A: 

I think you're looking for the MultiWidget, you can simply give it 2 regular widgets and it will render the combination.

WoLpH
+2  A: 

Here you have a ready example(taken from my blog):

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

Example how to use:

>>> 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'}
Dominik Szopa
One of the fields is a `CharField` that is rendered with `HiddenInput`. Any Idea how can this be populated initially (in the constructor probably)?
Emil Ivanov