English 中文(简体)
Django MultiWidget Phone Number Field
原标题:

I want to create a field for phone number input that has 2 text fields (size 3, 3, and 4 respectively) with the common "(" ")" "-" delimiters. Below is my code for the field and the widget, I m getting the following error when trying to iterate the fields in my form during initial rendering (it happens when the for loop gets to my phone number field):

Caught an exception while rendering: NoneType object is unsubscriptable

class PhoneNumberWidget(forms.MultiWidget):
    def __init__(self,attrs=None):
        wigs = (forms.TextInput(attrs={ size : 3 , maxlength : 3 }),
                forms.TextInput(attrs={ size : 3 , maxlength : 3 }),
                forms.TextInput(attrs={ size : 4 , maxlength : 4 }))
        super(PhoneNumberWidget, self).__init__(wigs, attrs)

    def decompress(self, value):
        return value or None

    def format_output(self, rendered_widgets):
        return  ( +rendered_widgets[0]+ ) +rendered_widgets[1]+ - +rendered_widgets[2]

class PhoneNumberField(forms.MultiValueField):
    widget = PhoneNumberWidget
    def __init__(self, *args, **kwargs):
        fields=(forms.CharField(max_length=3), forms.CharField(max_length=3), forms.CharField(max_length=4))
        super(PhoneNumberField, self).__init__(fields, *args, **kwargs)
    def compress(self, data_list):
        if data_list[0] in fields.EMPTY_VALUES or data_list[1] in fields.EMPTY_VALUES or data_list[2] in fields.EMPTY_VALUES:
            raise fields.ValidateError(u Enter valid phone number )
        return data_list[0]+data_list[1]+data_list[2]

class AdvertiserSumbissionForm(ModelForm):
    business_phone_number = PhoneNumberField(required=True)
最佳回答

I took hughdbrown s advise and modified USPhoneNumberField to do what I need. The reason I didn t use it initially was that it stores phone numbers as XXX-XXX-XXXX in the DB, I store them as XXXXXXXXXX. So I over-rode the clean method:

class PhoneNumberField(USPhoneNumberField):
    def clean(self, value):
        super(USPhoneNumberField, self).clean(value)
        if value in EMPTY_VALUES:
            return u  
        value = re.sub( ((|)|s+) ,   , smart_unicode(value))
        m = phone_digits_re.search(value)
        if m:
            return u %s%s%s  % (m.group(1), m.group(2), m.group(3))
        raise ValidationError(self.error_messages[ invalid ])
问题回答

This uses widget.value_from_datadict() to format the data so no need to subclass a field, just use the existing USPhoneNumberField. Data is stored in db like XXX-XXX-XXXX.

from django import forms

class USPhoneNumberMultiWidget(forms.MultiWidget):
    """
    A Widget that splits US Phone number input into three <input type= text > boxes.
    """
    def __init__(self,attrs=None):
        widgets = (
            forms.TextInput(attrs={ size : 3 , maxlength : 3 ,  class : phone }),
            forms.TextInput(attrs={ size : 3 , maxlength : 3 ,  class : phone }),
            forms.TextInput(attrs={ size : 4 , maxlength : 4 ,  class : phone }),
        )
        super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            return value.split( - )
        return (None,None,None)

    def value_from_datadict(self, data, files, name):
        value = [u  ,u  ,u  ]
        # look for keys like name_1, get the index from the end
        # and make a new list for the string replacement values
        for d in filter(lambda x: x.startswith(name), data):
            index = int(d[len(name)+1:]) 
            value[index] = data[d]
        if value[0] == value[1] == value[2] == u  :
            return None
        return u %s-%s-%s  % tuple(value)

use in a form like so:

from django.contrib.localflavor.us.forms import USPhoneNumberField
class MyForm(forms.Form):
    phone = USPhoneNumberField(label="Phone", widget=USPhoneNumberMultiWidget())

I think the value_from_datadict() code can be simplified to:


class USPhoneNumberMultiWidget(forms.MultiWidget):
    """
    A Widget that splits US Phone number input into three  boxes.
    """
    def __init__(self,attrs=None):
        widgets = (
            forms.TextInput(attrs={ size : 3 , maxlength : 3 ,  class : phone }),
            forms.TextInput(attrs={ size : 3 , maxlength : 3 ,  class : phone }),
            forms.TextInput(attrs={ size : 4 , maxlength : 4 ,  class : phone }),
        )
        super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs)

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

    def value_from_datadict(self, data, files, name):
        values = super(USPhoneNumberMultiWidget, self).value_from_datadict(data, files, name)
        return u %s-%s-%s  % values

The value_from_datadict() method for MultiValueWidget already does the following:


    def value_from_datadict(self, data, files, name):
        return [widget.value_from_datadict(data, files, name +  _%s  % i) for i, widget in enumerate(self.widgets)]

Sometimes it is useful to fix the original problem rather than redoing everything. The error you got, "Caught an exception while rendering: NoneType object is unsubscriptable" has a clue. There is a value returned as None(unsubscriptable) when a subscriptable value is expected. The decompress function in PhoneNumberWidget class is a likely culprit. I would suggest returning [] instead of None.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签