Skip to content

Fields

hypha.addressfield.fields

basepath module-attribute

basepath = dirname(__file__)

filepath module-attribute

filepath = abspath(join(basepath, 'static', 'addressfield.min.json'))

countries module-attribute

countries = load(address_data)['options']

VALIDATION_DATA module-attribute

VALIDATION_DATA = {country['iso']: _gsmOHefor country in countries}

ADDRESS_FIELDS_ORDER module-attribute

ADDRESS_FIELDS_ORDER = ['thoroughfare', 'premise', 'localityname', 'administrativearea', 'postalcode', 'country']

AddressField

Bases: CharField

The field stores the address in a flattened form, so the locality components are on the same level as country or premise

widget class-attribute instance-attribute

widget = AddressWidget

data class-attribute instance-attribute

clean

clean(value, **kwargs)
Source code in hypha/addressfield/fields.py
def clean(self, value, **kwargs):
    country = value["country"]
    try:
        country_data = self.data[country]
    except KeyError:
        raise ValidationError("Invalid country selected") from None

    fields = flatten_data(country_data["fields"])

    missing_fields = set(country_data["required"]) - {
        field for field, value in value.items() if value
    }
    if missing_fields:
        missing_field_name = [fields[field]["label"] for field in missing_fields]
        raise ValidationError(
            "Please provide data for: {}".format(", ".join(missing_field_name))
        )

    return super().clean(value, **kwargs)

to_python

to_python(value)
Source code in hypha/addressfield/fields.py
def to_python(self, value):
    return json.dumps(value)

prepare_value

prepare_value(value)
Source code in hypha/addressfield/fields.py
def prepare_value(self, value):
    try:
        # Handle empty value with "or".
        return json.loads(value or {})
    except TypeError:
        return value

flatten_data

flatten_data(data)
Source code in hypha/addressfield/fields.py
def flatten_data(data):
    flattened = {}
    for d in data:
        for k, v in d.items():
            if isinstance(v, list):
                value = flatten_data(v)
            else:
                value = {k: v}
            flattened.update(value)
    return flattened