Django Exception Value: 'TextInput' object has no attribute 'clean'

1k views Asked by At

I met the following problem with Django 1.6.

I try to create a custom MultiValueField and catch an error during submitting the form. Error appears in "django/forms/fields.py in clean, line 993":

clean_data.append(field.clean(field_value))

Local vars:
field   <django.forms.widgets.TextInput object at 0x105f608d0>
field_value     u'+7'

It seems like django tries to call clean method which doesn't exist in django.forms.widgets.TextInput

So I have a question - is it me doing smth wrong or is it a django bug?

My code of custom field:

from django import forms


class PhoneWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        _widgets = (
            forms.HiddenInput(attrs={'value': '+7'}),
            forms.TextInput(attrs={'class': 'form-control'}),
        )
        super(PhoneWidget, self).__init__(_widgets, attrs)

    def decompress(self, value):
        if value:
            return value
        return [None, None]

    def format_output(self, rendered_widgets):
        from django.template.loader import render_to_string
        return render_to_string('parts/phone.html', {
                'phone_code': rendered_widgets[0],
                'phone_number': rendered_widgets[1]
            })


class PhoneField(forms.MultiValueField):
    widget = PhoneWidget()

    def __init__(self, required=False):
        phone_code = forms.TextInput()
        phone_number = forms.TextInput()
        super(PhoneField, self).__init__(required=required, fields=(phone_code, phone_number))

    def compress(self, data_list):
        return data_list

Form code:

class OfficeForm(ModelForm):
    phone = custom_fields.PhoneField()

    class Meta:
        model = Office
        exclude = ['user']
        error_messages = {
            'name': {
                'required': "This is a required field",
            },
        }

    def clean_phone(self):
        data = self.cleaned_data['phone']
        return data

The question is closed.

The problem was that I declared custom fields as widgets...

phone_code = forms.TextInput()
phone_number = forms.TextInput()

It had to be

phone_code = forms.CharField()
phone_number = forms.CharField()
0

There are 0 answers