A Django package to manage and parse addresses with geocoding support.
Project description
django-autoparsed-address-field
django-autoparsed-address-field provides a set of pre-defined models and utilities to manage, normalize, and geocode address data in Django projects. It also offers a custom AutoParsedAddressField that integrates seamlessly into your models and automatically parses raw address strings.
Features
- Pre-defined Models:
Country,State,Locality, andAddressmodels included.- Designed with foreign key relationships to represent geographic data.
- Automatic Address Parsing:
- Parse raw address strings into structured fields.
- Geocoding Providers:
- Supports ArcGIS (via
geopy) and Scourgify for geocoding and normalization.
- Supports ArcGIS (via
- Custom Address Field:
- The
AutoParsedAddressFieldcan be added to any model to handle address data automatically.
- The
- Admin Mixin:
- Simplifies admin integration, displaying a text input for new records and a dropdown for existing ones.
Installation
Install the package via pip:
pip install django-autoparsed-address-field
Usage
1. Add autoparsed_address_field to INSTALLED_APPS
Add the app to your Django project's INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
...
"autoparsed_address_field",
]
2. Run Migrations
Apply the migrations to create the provided models:
python manage.py makemigrations autoparsed_address_field
python manage.py migrate
3. Use the Pre-defined Models
The following models are included in the app and ready for use:
Country
Represents a country, with a unique ISO code.
from autoparsed_address_field.models import Country
country = Country.objects.create(name="United States", code="USA")
State
Represents a state or region within a country.
from autoparsed_address_field.models import State
state = State.objects.create(name="California", code="CA", country=country)
Locality
Represents a city or locality within a state.
from autoparsed_address_field.models import Locality
locality = Locality.objects.create(name="Los Angeles", postal_code="90001", state=state)
Address
Represents an address, with optional latitude and longitude.
from autoparsed_address_field.models import Address
address = Address.objects.create(
address_line_1="123 Main Street",
address_line_2="Apt 4B",
locality=locality,
raw="123 Main Street, Los Angeles, CA 90001, USA",
)
4. Use AutoParsedAddressField
The AutoParsedAddressField provides seamless integration for address parsing in your own models.
Example:
from django.db import models
from autoparsed_address_field.fields import AutoParsedAddressField
class YourModel(models.Model):
address = AutoParsedAddressField()
# When a new instance is saved, the address will be automatically parsed.
your_instance = YourModel.objects.create(
address=Address.objects.create(raw="1600 Pennsylvania Ave NW, Washington, DC")
)
print(your_instance.address.formatted)
5. Use AutoParsedAddressAdminMixin
The AutoParsedAddressAdminMixin simplifies admin integration for models using AutoParsedAddressField.
Example:
from django.contrib import admin
from autoparsed_address_field.admin_mixins import AutoParsedAddressAdminMixin
from .models import YourModel
@admin.register(YourModel)
class YourModelAdmin(AutoParsedAddressAdminMixin, admin.ModelAdmin):
list_display = ("id", "address")
Admin Behavior:
- New Records: Displays a text input for raw address entry.
- Existing Records: Displays a dropdown for selecting related
Addressobjects.
6. Using the address_parsed Signal
The address_parsed signal allows you to hook into the address parsing process. This can be useful if you want to perform additional actions, such as logging, updating related models, or triggering external services when an address is successfully parsed.
Example Usage:
from autoparsed_address_field.signals import address_parsed
import logging
logger = logging.getLogger(__name__)
# Define a signal handler
def handle_address_parsed(sender, model_name, address_instance, **kwargs):
"""
Signal handler for the `address_parsed` signal.
Args:
sender: The class of the sender.
model_name: The name of the model where the address was parsed.
address_instance: The instance of the Address model that was parsed.
**kwargs: Additional keyword arguments.
"""
logger.info(f"Address parsing completed for model: {model_name}")
logger.info(f"Formatted Address: {address_instance.formatted}")
logger.info(f"Latitude: {address_instance.latitude}, Longitude: {address_instance.longitude}")
# Perform additional actions here, such as notifying a user or updating related data
# Connect the signal to the handler
address_parsed.connect(handle_address_parsed, dispatch_uid="handle_address_parsed_signal")
Explanation:
- Signal Handler: The
handle_address_parsedfunction is invoked whenever the signal is dispatched. It receives the sender, the model name, the parsed address instance, and any additional arguments. - Logging: The handler logs the parsed address details, including the formatted address, latitude, and longitude.
- Connecting the Signal: The
address_parsed.connectmethod connects the handler to the signal. Thedispatch_uidensures the handler is not connected multiple times.
This setup allows you to extend the functionality of the package by reacting to successful address parsing events in a modular way.
Settings
Geocoding Provider
The ADDRESS_GEOCODER_PROVIDER setting determines which geocoding provider the package uses to parse and normalize addresses. This flexibility allows you to select the provider that best suits your needs based on data accuracy, cost, or specific features.
Add the following to your settings.py file to configure the geocoding provider:
ADDRESS_GEOCODER_PROVIDER = "arcgis" # Options: "arcgis", "scourgify"
Rationale for Choosing a Provider
| Provider | Description | Rationale |
|---|---|---|
| ArcGIS | Leverages Esri's ArcGIS geocoding service via the geopy library. |
Best for applications requiring high accuracy, global coverage, and detailed geospatial data. |
| Scourgify | Uses usaddress-scourgify for parsing and normalizing US addresses. |
Ideal for US-based projects where simplicity and no external dependencies are preferred. |
Example Configuration:
# settings.py
ADDRESS_GEOCODER_PROVIDER = "arcgis" # Use Esri's ArcGIS geocoder
Switching Between Providers
You can easily switch between providers by updating the ADDRESS_GEOCODER_PROVIDER setting. For example, to use Scourgify:
ADDRESS_GEOCODER_PROVIDER = "scourgify" # Use Scourgify for address parsing
This modular approach allows your application to adapt to different geographic or business requirements without changing your codebase.
Running Tests
To test the package, set up a local environment and run:
pytest autoparsed_address_field/tests
Contributing
Contributions are welcome! Feel free to submit issues or pull requests.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_autoparsed_address_field-1.0.2.tar.gz.
File metadata
- Download URL: django_autoparsed_address_field-1.0.2.tar.gz
- Upload date:
- Size: 18.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.9.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
df60a1e5e6bfc54670f8845ce2ae08dd4dd22a846ac8d1617a05141f7beeb349
|
|
| MD5 |
4d1e142cd5773b5d29a60361b3d01a4e
|
|
| BLAKE2b-256 |
341ec16d748d75f5a5a5557202f3d100b3e7738f9e933e59e5b2de9fd099773c
|
File details
Details for the file django_autoparsed_address_field-1.0.2-py3-none-any.whl.
File metadata
- Download URL: django_autoparsed_address_field-1.0.2-py3-none-any.whl
- Upload date:
- Size: 26.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.9.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c8fcf46d5b2bd5e52c79d8d80cbf5a0152d2924ce24794a8b50f22618c597cc7
|
|
| MD5 |
13bc38a979a201e655d36f9bd44660e1
|
|
| BLAKE2b-256 |
bc18dd508014557a65a545ca8170130498286441e3554fab6d1b4a3a44613314
|