我有一个用于地址信息的表格。其中一个领域是地址国家。目前,这只是一个文本框。我想为此(ISO 3166个国家 /地区)下拉列表。我是Django Newbie,所以我什至还没有使用Django选择的小部件。什么是一个好方法?

硬编码在某个地方文件中的选择?将它们放在数据库中?在模板中?

有帮助吗?

解决方案 3

最终使用以下片段,基本上定义了两个字符乡村代码的元组。此外,它定义了一个名为countryfield的自定义字段类型,并将选项参数默认为上述元组。这会自动渲染为下拉列表。

http://djangosnippets.org/snippets/494/

其他提示

查看 ”选择“ Charfield的参数。

您可能还想看看 django-intries.

Django国家

from django_countries.fields import CountryField

class Foo(models.Model):
    country = CountryField()

Django国家

from django_countries.countries import COUNTRIES

class CountryForm(forms.Form):
      country= forms.ChoiceField(COUNTRIES)

这是一个有国家(不仅)的不错的图书馆: Pycountry

它的主要优点是,与其他解决方案中的硬编码国家相比,它是Debian软件包PKG-ISOCODES的包装纸(因此可以自动更新)。它也有翻译。

因此,如果出现新国家或将合并现有国家,则无需更改代码。

我发现使用此库并使用模型国家 /地区创建一个简单的Django应用程序很有用

然后,您可以通过自定义的Django-Admin命令来填充并保留“国家”表格,如下所述: 编写自定义django-admin命令

正如以前的答案所述,有一个 CountryFielddjango-countries. 。这是一个模型字段。

如果需要以平淡的形式(不是模型表格)的表单字段,则 django-countries v3.x(绝对在3.3中测试)可以使用以下内容:

from django_countries.data import COUNTRIES

class MyForm(forms.Form):
    country = forms.ChoiceField(sorted(COUNTRIES.items()))

将它们放在数据库中是更好的方法。方便管理。

链接到包: django-intries
如果寻找如何以形式进行操作:

$ pip install django-countries

>>> from django_countries.data import COUNTRIES

>>> Country = forms.ChoiceField(choices = sorted(COUNTRIES.items()))

这是解决方案:

from django_countries.fields import CountryField

class Foo(TimeStampedModel):

    country = CountryField()

我通过使用 multiple=True:

from django_countries.fields import CountryField    

class UserProfile(models.Model):
    countries = CountryField(multiple=True)

您可以在文档中阅读有关它的更多信息:

https://github.com/smileychris/django-countries

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top