代码之家  ›  专栏  ›  技术社区  ›  User

Django:国家下拉列表?

  •  19
  • User  · 技术社区  · 14 年前

    我有一张地址信息表。其中一个字段用于地址国家。目前这只是一个文本框。我想要一个下拉列表(ISO 3166国家)。我是一个django新手,所以我还没有使用django select小部件。做这件事的好方法是什么?

    在某个地方硬编码文件中的选项?把它们放到数据库里?在模板中?

    11 回复  |  直到 6 年前
        1
  •  32
  •   Juho Vepsäläinen    9 年前

    退房 choices “charfield的参数。

    你可能还想看看 django-countries .

        2
  •  15
  •   aehlke    9 年前

    Django Countries

    from django_countries.fields import CountryField
    
    class Foo(models.Model):
        country = CountryField()
    
        3
  •  9
  •   User    14 年前

    最后使用下面的代码片段,它基本上定义了两个字符的国家代码的元组。此外,它还定义了一个名为CountryField的自定义字段类型,并将choices参数默认为上述定义的元组。这将自动呈现为下拉列表。

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

        4
  •  8
  •   Asinox    14 年前

    Django国家

    from django_countries.countries import COUNTRIES
    
    class CountryForm(forms.Form):
          country= forms.ChoiceField(COUNTRIES)
    
        6
  •  3
  •   Strikki    11 年前

    这是一个不错的图书馆,有很多国家(不仅如此): pycountry

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

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

    我发现使用这个库并创建一个简单的django应用程序,例如使用示范国家

    然后,您可以通过自定义django admin命令填充和更新“country”表,如下所述: Writing custom django-admin commands

        7
  •  2
  •   Wtower Campi    10 年前

    正如前面的答案所述,有一个 CountryField 在里面 django-countries . 这是一个模型字段。

    如果普通表单(而不是模型表单)中需要表单字段,请在 Django国家 v3.x(在3.3中明确测试)可以使用以下内容:

    from django_countries.data import COUNTRIES
    
    class MyForm(forms.Form):
        country = forms.ChoiceField(sorted(COUNTRIES.items()))
    
        8
  •  1
  •   andyshi    13 年前

    把它们放到数据库中是更好的方法。便于管理。

        9
  •  1
  •   tuxvador    6 年前

    链接到包: django-countries
    如果在表单中查找如何执行此操作:

    $ pip install django-countries
    
    >>> from django_countries.data import COUNTRIES
    
    >>> Country = forms.ChoiceField(choices = sorted(COUNTRIES.items()))
    
        10
  •  0
  •   josephmisiti    10 年前

    解决方案如下:

    from django_countries.fields import CountryField
    
    class Foo(TimeStampedModel):
    
        country = CountryField()
    
        11
  •  0
  •   spedy    6 年前

    我用 multiple=True :

    from django_countries.fields import CountryField    
    
    class UserProfile(models.Model):
        countries = CountryField(multiple=True)
    

    您可以在文档中了解更多信息:

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