一种选择是使用 Geopy 在 Yahoo 或 Google Maps 等人上查找地址,然后返回与其匹配的地址的完整地址。您可能需要注意返回地址中的公寓号码是否被截断(例如,“221 Amsterdam Av #330”变为“221 AMSTERDAM AVENUE”)。此外,您还将获得城市/州/国家/地区信息,用户可能还会缩写或拼写错误。
如果有多个匹配项,您可以提示用户反馈哪个是他们的地址。在不匹配的情况下,您也可以让用户知道,并可能允许保存地址,这取决于有效地址的重要性以及您对地址查找提供者有效性的信任程度。
关于在表单与模型中进行这种规范化,我不知道首选的 Django 做事方式是什么,但我的偏好是在表单中,例如:
def clean(self):
# check address via some self-defined helper function
matches = my_helper_address_matcher(address, city, state, zip)
if not matches:
raise forms.ValidationError("Your address couldn't be found...")
elif len(matches) > 1:
# add javascript into error so the user can select
# the address that matches? maybe there is a cleaner way to do this
raise forms.ValidationError('Did you mean...')
你可以在模型(或一些 helpers.py 文件)中抛出这个查找函数,以防你想在其他领域重用它