Custom Address Field in Django Model

What is the common practice of representing email addresses in Django models? Is there a library for custom model fields that includes email address fields and can handle validation and formatting?

If there is no library, how can I write it? Is it possible to imagine a composite field (a field that is serialized into multiple columns in db) in django? The hope is that this eliminates the need to combine queries.

+4
source share
1 answer

I don’t know any form fields for addresses, but you can use localflavor to check the input and combo MultiWidget and MultiValueField to create an address field. My 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, but insert a little here. This information should lead you in the right direction.

Note: from November 21, 2013 localflavor has been moved to an external package ( available in PyPi ).

+6
source

Source: https://habr.com/ru/post/1299777/


All Articles