开发者

Custom address field in Django Model

What's the common practice to represent postal addresses in Django models? Is there a library for custom model fields that include postal address fields and potentially handle validation and formatting?

If no library exists, how can I write one? Can I represent a composite开发者_运维技巧 field (a field that gets serialized to multiple columns in db) in django? The hope is that this eliminates the need to having a joining query.


I don't know of a single form field for addresses, but you can use localflavor to validate the input and a combo of MultiWidget and MultiValueField for creating an address field. Mine looks something like this:

class SplitAddressWidget(forms.MultiWidget):
    def __init__(self, attrs=None):     
        widgets = []
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        super(SplitAddressWidget, self).__init__(widgets, attrs)
    ...

class SplitAddressField(forms.MultiValueField):
    widget = SplitAddressWidget
    def __init__(self, *args, **kwargs):
        fields = (
                forms.CharField(required=kwargs['required']),
                forms.CharField(required=0),    
                forms.CharField(required=kwargs['required']),
                USStateField(required=kwargs['required']),
                USZipCodeField(required=kwargs['required']),
            )
        super(SplitAddressField, self).__init__(fields, *args, **kwargs)
    ...

There is more code involved, but it is a bit much to paste in here. This info should get you headed in the right direction.

Note: as of Nov. 21, 2013 localflavor has been moved to an external package (available on PyPi).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜