furious-luke / django-address

A Django address model and field. Addresses may be specified by address components or by performing an automatic Google Maps lookup.
BSD 3-Clause "New" or "Revised" License
430 stars 180 forks source link

Use __str__ logic for serializing formatted value if it is missing #157

Closed BenQuigley closed 2 years ago

BenQuigley commented 3 years ago

The widget for this app, in address.widgets.AddressWidget.render, prepopulates the address form with the value of address.formatted if it exists, but otherwise it stays blank.

However, an address can be created with just address.models.Address.create(address="north pole"), and this populates the Address.raw value and nothing else. So making a widget using an address like that as its instance / initial value results in a weird state where the widget was created correctly, but there is no initial value in the widget.

The __str__ method of the Address model contains logic that addresses this: it returns the formatted value if one exists, otherwise it tries to construct one from the locality fields, otherwise it falls back to the raw value. Using this method to populate the formatted value in to_dict fixes this problem of the widget.

Screen Shot 2021-09-04 at 11 12 41 AM
furious-luke commented 3 years ago

Hi @BenQuigley, thanks for the PR, it's very much appreciated!

I wonder whether we actually want to force setting the value of formatted to raw during the creation of the address (when formatted is empty, of course) as opposed to when returning values to the UI? It probably makes sense to require formatted to exist, guaranteeing a human readable value at all times. What are your thoughts?

BenQuigley commented 3 years ago

Hm, looks like that is already happening in the _to_python function. Sure, that sounds good to me