如果您只想拥有一个国家 ChoiceField 而不安装 django-choices,您可以创建一个额外的文件,其中包含一个包含来自 Wikipedia Iso Country Codes 的所有选项的元组:
import csv
# Get the file from: "http://geohack.net/gis/wikipedia-iso-country-codes.csv"
with open("wikipedia-iso-country-codes.csv") as f:
file = csv.DictReader(f, delimiter=',')
country_names = [line['English short name lower case'] for line in file]
# Create a tuple with the country names
with open("country_names.py", 'w') as f:
f.write('COUNTRY_CHOICES = (\n')
for c in country_names:
f.write(f' ("{c}", "{c}"),\n')
f.write(')')
创建的 country_names.py 文件如下所示:
COUNTRY_CHOICES = (
("Afghanistan", "Afghanistan"),
("Åland Islands", "Åland Islands"),
("Albania", "Albania"),
("Algeria", "Algeria"),
("American Samoa", "American Samoa"),
...
)
然后您可以像这样在表单中使用 COUNTRY_CHOICES:
from django import forms
from country_names import COUNTRY_CHOICES
class CountryForm(forms.Form):
country= forms.ChoiceField(choices=COUNTRY_CHOICES)