• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.tx/H19-Apr-2018-96

django_countries/H19-Apr-2018-42,99232,745

django_countries.egg-info/H03-May-2022-789503

CHANGES.rstH A D19-Apr-20187.1 KiB297170

LICENSEH A D19-Apr-20181 KiB2219

MANIFEST.inH A D19-Apr-2018121 66

PKG-INFOH A D19-Apr-201826.4 KiB789503

README.rstH A D19-Apr-201812.5 KiB467309

setup.cfgH A D19-Apr-20181.5 KiB8271

setup.pyH A D19-Apr-201860 52

tox.iniH A D19-Apr-20181.9 KiB8173

README.rst

1================
2Django Countries
3================
4
5.. image:: https://badge.fury.io/py/django-countries.svg
6    :alt: PyPI version
7    :target: https://badge.fury.io/py/django-countries
8
9.. image:: https://travis-ci.org/SmileyChris/django-countries.svg?branch=master
10    :alt: Build status
11    :target: http://travis-ci.org/SmileyChris/django-countries
12
13.. image:: https://codecov.io/gh/SmileyChris/django-countries/branch/master/graph/badge.svg
14    :alt: Coverage status
15    :target: https://codecov.io/gh/SmileyChris/django-countries
16
17
18A Django application that provides country choices for use with forms, flag
19icons static files, and a country field for models.
20
21.. contents:: Topics
22
23
24Installation
25============
26
271. ``pip install django-countries``
282. Add ``django_countries`` to ``INSTALLED_APPS``
29
30For more accurate sorting of translated country names, install the optional
31pyuca_ package.
32
33.. _pyuca: https://pypi.python.org/pypi/pyuca/
34
35
36CountryField
37============
38
39A country field for Django models that provides all ISO 3166-1 countries as
40choices.
41
42``CountryField`` is based on Django's ``CharField``, providing choices
43corresponding to the official ISO 3166-1 list of countries (with a default
44``max_length`` of 2).
45
46Consider the following model using a ``CountryField``:
47
48  .. code:: python
49
50    from django.db import models
51    from django_countries.fields import CountryField
52
53    class Person(models.Model):
54        name = models.CharField(max_length=100)
55        country = CountryField()
56
57Any ``Person`` instance will have a ``country`` attribute that you can use to
58get details of the person's country:
59
60  .. code:: python
61
62    >>> person = Person(name='Chris', country='NZ')
63    >>> person.country
64    Country(code='NZ')
65    >>> person.country.name
66    'New Zealand'
67    >>> person.country.flag
68    '/static/flags/nz.gif'
69
70This object (``person.country`` in the example) is a ``Country`` instance,
71which is described below.
72
73Use ``blank_label`` to set the label for the initial blank choice shown in
74forms:
75
76  .. code:: python
77
78    country = CountryField(blank_label='(select country)')
79
80
81Multi-choice
82------------
83
84This field can also allow multiple selections of countries (saved as a comma
85separated string). The field will always output a list of countries in this
86mode. For example:
87
88  .. code:: python
89
90    class Incident(models.Model):
91        title = models.CharField(max_length=100)
92        countries = CountryField(multiple=True)
93
94    >>> for country in Incident.objects.get(title='Pavlova dispute').countries:
95    ...     print(country.name)
96    Australia
97    New Zealand
98
99
100The ``Country`` object
101----------------------
102
103An object used to represent a country, instanciated with a two character
104country code.
105
106It can be compared to other objects as if it was a string containing the
107country code and when evaluated as text, returns the country code.
108
109name
110  Contains the full country name.
111
112flag
113  Contains a URL to the flag. If you page could have lots of different flags
114  then consider using ``flag_css`` instead to avoid excessive HTTP requests.
115
116flag_css
117  Output the css classes needed to display an HTML element as the correct flag
118  from within a single sprite image that contains all flags. For example:
119
120  .. code:: jinja
121
122    <link rel="stylesheet" href="{% static 'flags/sprite.css' %}">
123    <i class="{{ country.flag_css }}"></i>
124
125  For multiple flag resolutions, use ``sprite-hq.css`` instead and add the
126  ``flag2x``, ``flag3x``, or ``flag4x`` class. For example:
127
128  .. code:: jinja
129
130    <link rel="stylesheet" href="{% static 'flags/sprite-hq.css' %}">
131    Normal: <i class="{{ country.flag_css }}"></i>
132    Bigger: <i class="flag2x {{ country.flag_css }}"></i>
133
134  You might also want to consider using ``aria-label`` for better
135  accessibility:
136
137  .. code:: jinja
138
139    <i class="{{ country.flag_css }}"
140        aria-label="{% blocktrans with country_code=country.code %}
141            {{ country_code }} flag
142        {% endblocktrans %}"></i>
143
144unicode_flag
145  A unicode glyph for the flag for this country. Currently well-supported in
146  iOS and OS X. See https://en.wikipedia.org/wiki/Regional_Indicator_Symbol
147  for details.
148
149alpha3
150  The three letter country code for this country.
151
152numeric
153  The numeric country code for this country (as an integer).
154
155numeric_padded
156  The numeric country code as a three character 0-padded string.
157
158
159``CountrySelectWidget``
160-----------------------
161
162A widget is included that can show the flag image after the select box
163(updated with JavaScript when the selection changes).
164
165When you create your form, you can use this custom widget like normal:
166
167  .. code:: python
168
169    from django_countries.widgets import CountrySelectWidget
170
171    class PersonForm(forms.ModelForm):
172        class Meta:
173            model = models.Person
174            fields = ('name', 'country')
175            widgets = {'country': CountrySelectWidget()}
176
177Pass a ``layout`` text argument to the widget to change the positioning of the
178flag and widget. The default layout is:
179
180  .. code:: python
181
182    '{widget}<img class="country-select-flag" id="{flag_id}" style="margin: 6px 4px 0" src="{country.flag}">'
183
184
185Custom forms
186============
187
188If you want to use the countries in a custom form, use the model field's custom
189form field to ensure the translatable strings for the country choices are left
190lazy until the widget renders:
191
192  .. code:: python
193
194    from django_countries.fields import CountryField
195
196    class CustomForm(forms.Form):
197        country = CountryField().formfield()
198
199Use ``CountryField(blank=True)`` for non-required form fields, and
200``CountryField(blank_label='(Select country)')`` to use a custom label for the
201initial blank option.
202
203You can also use the CountrySelectWidget_ as the widget for this field if you
204want the flag image after the select box.
205
206
207Get the countries from Python
208=============================
209
210Use the ``django_countries.countries`` object instance as an iterator of ISO
2113166-1 country codes and names (sorted by name).
212
213For example:
214
215  .. code:: python
216
217    >>> from django_countries import countries
218    >>> dict(countries)['NZ']
219    'New Zealand'
220
221    >>> for code, name in list(countries)[:3]:
222    ...     print("{name} ({code})".format(name=name, code=code))
223    ...
224    Afghanistan (AF)
225    Åland Islands (AX)
226    Albania (AL)
227
228Country names are translated using Django's standard ``ugettext``.
229If you would like to help by adding a translation, please visit
230https://www.transifex.com/projects/p/django-countries/
231
232
233Template Tags
234=============
235
236If you have your country code stored in a different place than a `CountryField`
237you can use the template tag to get a `Country` object and have access to all
238of its properties:
239
240  .. code:: jinja
241
242    {% load countries %}
243    {% get_country 'BR' as country %}
244    {{ country.name }}
245
246If you need a list of countries, there's also a simple tag for that:
247
248  .. code:: jinja
249
250    {% load countries %}
251    {% get_countries as countries %}
252    <select>
253    {% for country in countries %}
254        <option>{{ country.name }}</option>
255    {% endfor %}
256    </select>
257
258
259Customization
260=============
261
262Customize the country list
263--------------------------
264
265Country names are taken from the official ISO 3166-1 list. If your project
266requires the use of alternative names, the inclusion or exclusion of specific
267countries then use the ``COUNTRIES_OVERRIDE`` setting.
268
269A dictionary of names to override the defaults.
270
271Note that you will need to handle translation of customised country names.
272
273Setting a country's name to ``None`` will exclude it from the country list.
274For example:
275
276  .. code:: python
277
278    from django.utils.translation import ugettext_lazy as _
279
280    COUNTRIES_OVERRIDE = {
281        'NZ': _('Middle Earth'),
282        'AU': None
283    }
284
285If you have a specific list of countries that should be used, use
286``COUNTRIES_ONLY``:
287
288  .. code:: python
289
290    COUNTRIES_ONLY = ['NZ', 'AU']
291
292or to specify your own country names, use a dictionary or two-tuple list
293(string items will use the standard country name):
294
295  .. code:: python
296
297    COUNTRIES_ONLY = [
298        'US',
299        'GB',
300        ('NZ', _('Middle Earth')),
301        ('AU', _('Desert')),
302    ]
303
304
305Show certain countries first
306----------------------------
307
308Provide a list of country codes as the ``COUNTRIES_FIRST`` setting and they
309will be shown first in the countries list (in the order specified) before all
310the alphanumerically sorted countries.
311
312If you want to sort these initial countries too, set the
313``COUNTRIES_FIRST_SORT`` setting to ``True``.
314
315By default, these initial countries are not repeated again in the
316alphanumerically sorted list. If you would like them to be repeated, set the
317``COUNTRIES_FIRST_REPEAT`` setting to ``True``.
318
319Finally, you can optionally separate these 'first' countries with an empty
320choice by providing the choice label as the ``COUNTRIES_FIRST_BREAK`` setting.
321
322
323Customize the flag URL
324----------------------
325
326The ``COUNTRIES_FLAG_URL`` setting can be used to set the url for the flag
327image assets. It defaults to::
328
329    COUNTRIES_FLAG_URL = 'flags/{code}.gif'
330
331The URL can be relative to the STATIC_URL setting, or an absolute URL.
332
333The location is parsed using Python's string formatting and is passed the
334following arguments:
335
336    * code
337    * code_upper
338
339For example: ``COUNTRIES_FLAG_URL = 'flags/16x10/{code_upper}.png'``
340
341No checking is done to ensure that a static flag actually exists.
342
343Alternatively, you can specify a different URL on a specific ``CountryField``:
344
345  .. code:: python
346
347    class Person(models.Model):
348        name = models.CharField(max_length=100)
349        country = CountryField(
350            countries_flag_url='//flags.example.com/{code}.png')
351
352
353Single field customization
354--------------------------
355
356To customize an individual field, rather than rely on project level settings,
357create a ``Countries`` subclass which overrides settings.
358
359To override a setting, give the class an attribute matching the lowercased
360setting without the ``COUNTRIES_`` prefix.
361
362Then just reference this class in a field. For example, this ``CountryField``
363uses a custom country list that only includes the G8 countries:
364
365  .. code:: python
366
367    from django_countries import Countries
368
369    class G8Countries(Countries):
370        only = [
371            'CA', 'FR', 'DE', 'IT', 'JP', 'RU', 'GB',
372            ('EU', _('European Union'))
373        ]
374
375    class Vote(models.Model):
376        country = CountryField(countries=G8Countries)
377        approve = models.BooleanField()
378
379
380Django Rest Framework
381=====================
382
383Django Countries ships with a ``CountryFieldMixin`` to make the
384`CountryField`_ model field compatible with DRF serializers. Use the following
385mixin with your model serializer:
386
387  .. code:: python
388
389    from django_countries.serializers import CountryFieldMixin
390
391    class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer):
392
393        class Meta:
394            model = models.Person
395            fields = ('name', 'email', 'country')
396
397This mixin handles both standard and `multi-choice`_ country fields.
398
399
400Django Rest Framework field
401---------------------------
402
403For lower level use (or when not dealing with model fields), you can use the
404included ``CountryField`` serializer field. For example:
405
406  .. code:: python
407
408    from django_countries.serializer_fields import CountryField
409
410    class CountrySerializer(serializers.Serializer):
411        country = CountryField()
412
413You can optionally instantiate the field with ``countries`` with a custom
414Countries_ instance.
415
416.. _Countries: `Single field customization`_
417
418
419OPTIONS request
420---------------
421
422When you request OPTIONS against a resource (using the DRF `metadata support`_)
423the countries will be returned in the response as choices:
424
425.. code:: text
426
427    OPTIONS /api/address/ HTTP/1.1
428
429    HTTP/1.1 200 OK
430    Content-Type: application/json
431    Allow: GET, POST, HEAD, OPTIONS
432
433    {
434    "actions": {
435      "POST": {
436        "country": {
437        "type": "choice",
438        "label": "Country",
439        "choices": [
440          {
441            "display_name": "Australia",
442            "value": "AU"
443          },
444          [...]
445          {
446            "display_name": "United Kingdom",
447            "value": "GB"
448          }
449        ]
450      }
451    }
452
453.. _metadata support: http://www.django-rest-framework.org/api-guide/metadata/
454
455
456REST output format
457------------------
458
459By default, the field will output just the country code. If you would rather
460have more verbose output, instantiate the field with ``country_dict=True``,
461which will result in the field having the following output structure::
462
463    {"code": "NZ", "name": "New Zealand"}
464
465Either the code or this dict output structure are acceptable as input
466irregardless of the ``country_dict`` argument's value.
467