### PyPI Credentials Setup (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Commands to install the keyring tool and set up PyPI credentials. This is necessary for publishing packages using tools like 'uv'.
```bash
uv tool install keyring
keyring set 'https://upload.pypi.org/legacy/' __token__
```
--------------------------------
### Django Model Usage and Country Properties
Source: https://github.com/smileychris/django-countries/blob/main/docs/quickstart.md
Demonstrates creating and querying Django model instances with the CountryField. Shows how to access country code, name, and flag.
```python
>>> from myapp.models import Person
>>> person = Person.objects.create(name="Chris", country="NZ")
>>> person.country
Country(code='NZ')
>>> person.country.name
'New Zealand'
>>> person.country.code
'NZ'
>>> person.country.flag
'/static/flags/nz.gif'
```
--------------------------------
### Transifex CLI Installation (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Command to install the Transifex CLI using the official installation script. This tool is required for managing translations.
```bash
# Install using the official installer
curl -o- https://raw.githubusercontent.com/transifex/cli/master/install.sh | bash
```
--------------------------------
### Complete Example of Django-Countries Settings
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/settings.md
An example demonstrating the combined use of multiple django-countries settings for comprehensive customization, including country naming, lists, display order, and flag URLs.
```python
from django.utils.translation import gettext_lazy as _
# Use common names
COUNTRIES_COMMON_NAMES = True
# Limit to North American countries
COUNTRIES_ONLY = ["US", "CA", "MX"]
# Show US first
COUNTRIES_FIRST = ["US"]
COUNTRIES_FIRST_BREAK = "───────────"
# Custom flag location
COUNTRIES_FLAG_URL = "images/flags/{code_upper}.png"
# Override US display
COUNTRIES_OVERRIDE = {
"US": {
"names": [_("United States"), _("USA")],
},
}
```
--------------------------------
### Install Django Countries using pip
Source: https://github.com/smileychris/django-countries/blob/main/README.md
This command installs the django-countries package using pip, making it available for use in your Django project. Ensure you have pip installed and configured correctly.
```bash
pip install django-countries
```
--------------------------------
### Display Country Properties in Django Templates
Source: https://github.com/smileychris/django-countries/blob/main/docs/quickstart.md
Provides examples of how to access and display country name and flag image URL within Django templates using the CountryField object.
```django
{{ person.name }} is from {{ person.country.name }}
```
--------------------------------
### Querying Django Models by Country
Source: https://github.com/smileychris/django-countries/blob/main/docs/quickstart.md
Illustrates how to filter Django model objects based on country code or country name using the CountryField.
```python
# Get all people from New Zealand
>>> Person.objects.filter(country='NZ')
# Query by country name
>>> Person.objects.filter(country__name='New Zealand')
```
--------------------------------
### Display Unicode Flag Emoji in Django Templates
Source: https://github.com/smileychris/django-countries/blob/main/docs/quickstart.md
Demonstrates how to display the Unicode flag emoji for a country in Django templates.
```django
```
--------------------------------
### Verify django-countries installation
Source: https://github.com/smileychris/django-countries/blob/main/docs/installation.md
Verifies that the django-countries package is installed correctly by importing the countries object and accessing a country code. This is a simple check to ensure the library is ready for use.
```python
>>> from django_countries import countries
>>> countries['NZ']
'New Zealand'
```
--------------------------------
### Install graphene-django for GraphQL
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
Installs the graphene-django library, which is required for integrating Django Countries with GraphQL. This is a prerequisite for using the GraphQL features.
```bash
pip install graphene-django
```
--------------------------------
### Django ModelForm with CountryField
Source: https://github.com/smileychris/django-countries/blob/main/docs/quickstart.md
Shows how to create a Django ModelForm that includes the CountryField. This automatically generates a country selection dropdown in the form.
```python
from django import forms
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ['name', 'country']
```
--------------------------------
### Install django-countries with optional pyuca support
Source: https://github.com/smileychris/django-countries/blob/main/docs/installation.md
Installs django-countries along with the optional pyuca package for improved Unicode sorting of country names. This is recommended for applications dealing with internationalization and non-ASCII characters.
```bash
pip install django-countries[pyuca]
```
--------------------------------
### Install django-filter
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/django_filters.md
Installs the django-filter library, which is a dependency for using the CountryFilter.
```bash
pip install django-filter
```
--------------------------------
### Add Changelog Entry (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Example command to create a new changelog entry file in the `changes/` directory. The filename format includes an issue/PR number and the type of change.
```bash
# With issue/PR number
echo "Your change description" > changes/123.bugfix.rst
```
--------------------------------
### Complete Example: Country Directory (Django Template)
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/templates.md
A comprehensive example demonstrating the use of multiple Django Countries template tags to build a country directory. It loads necessary tags (`countries`, `static`), includes high-resolution flag sprites with accessibility, and iterates through all countries to display their name and various code properties.
```django
{% load countries %}
{% load static %}
Country Directory
{% get_countries as countries %}
{% for country in countries %}
{{ country.name }}
Code:
{{ country.code }}
Alpha3:
{{ country.alpha3 }}
Numeric:
{{ country.numeric }}
IOC:
{{ country.ioc_code }}
{% endfor %}
```
--------------------------------
### Interact with CountryField in Django
Source: https://github.com/smileychris/django-countries/blob/main/docs/index.md
Shows examples of creating and accessing `CountryField` instances within a Django application. It illustrates how to set country codes, retrieve country objects, access country names, and get flag image paths.
```python
>>> from myapp.models import Person
>>> person = Person.objects.create(name="Chris", country="NZ")
>>> person.country
Country(code='NZ')
>>> person.country.name
'New Zealand'
>>> person.country.flag
'/static/flags/nz.gif'
```
--------------------------------
### Add django_countries to Django INSTALLED_APPS
Source: https://github.com/smileychris/django-countries/blob/main/docs/installation.md
Configures a Django project to use the django-countries app by adding it to the INSTALLED_APPS setting. This step is required for the package to function within a Django project.
```python
INSTALLED_APPS = [
# ...
'django_countries',
# ...
]
```
--------------------------------
### JSON Response for Company Query
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
This is an example JSON response for a GraphQL query that retrieves company information. It includes the company name and a list of countries associated with it, each with a code and name.
```json
{
"data": {
"company": {
"name": "Global Corp",
"countries": [
{
"code": "US",
"name": "United States"
},
{
"code": "GB",
"name": "United Kingdom"
},
{
"code": "AU",
"name": "Australia"
}
]
}
}
}
```
--------------------------------
### Accessing Custom Countries in Python
Source: https://context7.com/smileychris/django-countries/llms.txt
Demonstrates how to access and list custom country fields, specifically EU countries in this example. It shows retrieving a field object and iterating over its countries.
```python
from django_countries.fields import CountryField
class EuropeanCompany:
class _meta:
class get_field:
def __init__(self, name):
if name == "headquarters":
self.countries = ['DE', 'FR', 'ES', 'IT'] # Example EU countries
company = EuropeanCompany(name="EuroTech", headquarters="DE")
field = EuropeanCompany._meta.get_field("headquarters")
print(list(field.countries)) # Only EU countries
```
--------------------------------
### GraphQL Mutation for Creating a Person
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
This GraphQL mutation allows creating a new person record, including their name, email, and a country code. The mutation definition and schema setup are shown in Python using the graphene library.
```graphql
mutation {
createPerson(name: "John", email: "john@example.com", countryCode: "US") {
person {
id
name
country {
code
name
}
}
}
}
```
--------------------------------
### GraphQL Query for People with Country Names
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
An example GraphQL query to fetch a list of people, retrieving only their names and the names of their associated countries. This demonstrates fetching partial data for multiple records.
```graphql
query {
people {
name
country {
name
}
}
}
```
--------------------------------
### GraphQL Query for Full Person and Country Details
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
An example GraphQL query to retrieve a person's name, email, and all available country details (code, name, alpha3, numeric, iocCode). This showcases comprehensive data fetching.
```graphql
query {
person(id: 1) {
name
email
country {
code
name
alpha3
numeric
iocCode
}
}
}
```
--------------------------------
### Get Company with Multiple Countries
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
Retrieve company details along with a list of countries associated with it. This query allows you to fetch the company's name and the code and name for each of its countries.
```APIDOC
## GET /company/{id}
### Description
Fetches a company's details and its associated countries.
### Method
GET
### Endpoint
`/company/{id}`
#### Path Parameters
- **id** (integer) - Required - The unique identifier of the company.
#### Query Parameters
None
### Request Example
```graphql
query {
company(id: 1) {
name
countries {
code
name
}
}
}
```
### Response
#### Success Response (200)
- **data** (object)
- **company** (object)
- **name** (string) - The name of the company.
- **countries** (array of objects) - A list of countries associated with the company.
- **code** (string) - The ISO code of the country.
- **name** (string) - The name of the country.
#### Response Example
```json
{
"data": {
"company": {
"name": "Global Corp",
"countries": [
{
"code": "US",
"name": "United States"
},
{
"code": "GB",
"name": "United Kingdom"
},
{
"code": "AU",
"name": "Australia"
}
]
}
}
}
```
```
--------------------------------
### HTTP Response for Country Choices
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/drf.md
An example HTTP response containing JSON data that lists available country choices, suitable for dynamic form generation. The Content-Type is application/json.
```http
HTTP/1.1 200 OK
Content-Type: application/json
Allow: GET, POST, HEAD, OPTIONS
{
"actions": {
"POST": {
"country": {
"type": "choice",
"label": "Country",
"choices": [
{
"display_name": "Afghanistan",
"value": "AF"
},
{
"display_name": "Åland Islands",
"value": "AX"
},
{
"display_name": "Albania",
"value": "AL"
}
]
}
}
}
}
```
--------------------------------
### Django Forms and Widgets for Country Selection
Source: https://context7.com/smileychris/django-countries/llms.txt
Demonstrates how to integrate Django Countries fields and widgets into forms, including automatic integration with ModelForms, manual creation of forms using LazyTypedChoiceField, and utilizing CountrySelectWidget for displaying flags. Includes examples for custom widget layouts and handling blank labels.
```python
from django import forms
from django_countries.fields import CountryField
from django_countries.widgets import CountrySelectWidget
from myapp.models import Person
from django_countries.fields import LazyTypedChoiceField
from django_countries import countries
# ModelForm (automatic)
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ["name", "country"]
# Automatically uses LazyTypedChoiceField with LazySelect widget
# Manual form
class ManualForm(forms.Form):
country = LazyTypedChoiceField(choices=countries)
# With flag widget
class PersonFormWithFlag(forms.ModelForm):
class Meta:
model = Person
fields = ["name", "country"]
widgets = {
"country": CountrySelectWidget()
}
# Renders select with flag image that updates on selection
# Custom flag widget layout
class CustomFlagForm(forms.ModelForm):
class Meta:
model = Person
fields = ["name", "country"]
widgets = {
"country": CountrySelectWidget(
layout='{widget}'
)
}
# Form with custom blank label
class RegistrationForm(forms.Form):
name = forms.CharField(max_length=100)
# Uses blank_label from field definition
country = forms.ModelChoiceField(
queryset=Person.objects.none(),
empty_label="Choose your country"
)
```
--------------------------------
### GraphQL Integration with Graphene-Django
Source: https://context7.com/smileychris/django-countries/llms.txt
Details the integration of django-countries with Graphene-Django, providing a `CountryType` for GraphQL. It demonstrates how `CountryField` is automatically converted to `CountryType` in a DjangoObjectType, enabling querying of country details like code, name, and alpha3 code. Includes example GraphQL queries and responses.
```python
import graphene
from graphene_django import DjangoObjectType
from django_countries.graphql.types import Country as CountryType
from myapp.models import Person
class PersonType(DjangoObjectType):
# CountryField is automatically converted to CountryType
class Meta:
model = Person
fields = ["id", "name", "country"]
class Query(graphene.ObjectType):
person = graphene.Field(PersonType, id=graphene.Int(required=True))
def resolve_person(self, info, id):
return Person.objects.get(id=id)
schema = graphene.Schema(query=Query)
# GraphQL query:
# {
# person(id: 1) {
# name
# country {
# code
# name
# alpha3
# numeric
# iocCode
# }
# }
# }
# Response:
# {
# "data": {
# "person": {
# "name": "Chris",
# "country": {
# "code": "NZ",
# "name": "New Zealand",
# "alpha3": "NZL",
# "numeric": 554,
# "iocCode": "NZL"
# }
# }
# }
# }
```
--------------------------------
### Implement Django Rest Framework ViewSets for Country Data
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/drf.md
Provides example Django Rest Framework viewsets for handling Person and Company models, utilizing the previously defined serializers. This requires rest_framework.viewsets and myapp.models/serializers.
```python
from rest_framework import viewsets
from myapp.models import Person, Company
from myapp.serializers import PersonSerializer, CompanySerializer
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
class CompanyViewSet(viewsets.ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer
```
--------------------------------
### Get List of All Countries (Django Template Tag)
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/templates.md
Retrieves a list of all available `Country` objects and assigns them to a specified template variable. This tag is useful for populating dropdowns or lists of countries. Ensure the `countries` template tag library is loaded.
```django
{% get_countries as variable_name %}
```
--------------------------------
### Manual Release Step 5: Build and Publish (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Final steps in the manual release process: cleaning the distribution directory, building the package, and publishing it to PyPI.
```bash
rm -rf dist
uv build
uv publish
```
--------------------------------
### Manual Release Step 4: Commit and Tag (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
This step commits the version bump and changelog, then creates and pushes a Git tag for the release. It prepares the repository for building and publishing.
```bash
git add pyproject.toml CHANGES.md changes/
git commit -m "Preparing release $(uv version --short)"
git tag -a v$(uv version --short) -m "Release v$(uv version --short)"
git push --tags
git push
```
--------------------------------
### Manual Release Step 2 & 3: Bump Version and Build Changelog (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Commands to manually bump the version number and build the changelog using towncrier. This prepares the release artifacts before committing and tagging.
```bash
uv version --bump patch # or minor/major
uv run --group dev towncrier build --version $(uv version --short) --date "$(date '+%-d %B %Y')" --yes
```
--------------------------------
### Manual Release Step 1: Prepare Translations (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
This step involves pulling the latest translations from Transifex and committing them to the repository. It's part of the manual release process to ensure translations are up-to-date.
```bash
just tx-pull
git add django_countries/locale
git commit -m "Update translations from Transifex"
```
--------------------------------
### UV Environment Variables for Publishing (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Environment variables required for uv to use the keyring for publishing. These should typically be added to your shell's configuration file (e.g., .bashrc, .zshrc).
```bash
export UV_KEYRING_PROVIDER=subprocess
export UV_PUBLISH_USERNAME=__token__
```
--------------------------------
### Check All Project Checks (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Command to run all pre-commit checks, including formatting, linting, type checking, and tests. This should be run before submitting a pull request.
```bash
just check
```
--------------------------------
### ModelForm with Explicit Custom Widget
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/forms.md
An example of a Django ModelForm where the 'country' field is explicitly assigned the CountrySelectWidget, ensuring flag display.
```python
from django import forms
from django_countries.widgets import CountrySelectWidget
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ['name', 'country']
widgets = {
'country': CountrySelectWidget()
}
```
--------------------------------
### Standalone Form with CountryField and Widget
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/forms.md
A complete example of a standalone Django Form ('RegistrationForm') that includes a required country field utilizing both CountryField and CountrySelectWidget.
```python
from django import forms
from django_countries.fields import CountryField
from django_countries.widgets import CountrySelectWidget
class RegistrationForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
country = CountryField().formfield(
required=True,
widget=CountrySelectWidget()
)
```
--------------------------------
### Get Countries List from Python
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/field.md
Demonstrates how to access and iterate over the `django_countries.countries` object in Python to retrieve country codes and names. This allows for programmatic access to the country data.
```python
>>> from django_countries import countries
>>> dict(countries)["NZ"]
'New Zealand'
>>> for code, name in list(countries)[:3]:
... print(f"{name} ({code})")
...
Afghanistan (AF)
Åland Islands (AX)
Albania (AL)
```
--------------------------------
### Post-Release Development Version Bump (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Commands to reset the project to a development version after a release. This involves bumping the version to the next development iteration (e.g., X.Y.dev0) and committing the change.
```bash
uv version --bump minor
# Manually edit pyproject.toml to change version from X.Y.0 to X.Y.dev0
git add pyproject.toml
git commit -m "Back to development: X.Y.dev0"
git push
```
--------------------------------
### Countries Singleton API: Iteration and Lookup Operations
Source: https://context7.com/smileychris/django-countries/llms.txt
Explains how to use the Countries singleton to iterate through all available countries, perform various lookups (by name, alpha codes, numeric codes, IOC), and search using regular expressions.
```python
from django_countries import countries
from django.utils import translation
# Iteration (sorted by translated name)
for code, name in countries:
print(f"{code}: {name}")
# Lookup operations
print(countries.name("NZ")) # "New Zealand"
print(countries.alpha2("NZL")) # "NZ" (from alpha3)
print(countries.alpha2("554")) # "NZ" (from numeric)
print(countries.alpha2("nz")) # "NZ" (case insensitive)
print(countries.alpha3("NZ")) # "NZL"
print(countries.numeric("NZ")) # 554
print(countries.numeric("NZ", padded=True)) # "554"
print(countries.ioc_code("DE")) # "GER"
# Reverse lookup by name
code = countries.by_name("New Zealand")
print(code) # "NZ"
# Case-insensitive search
code = countries.by_name("new zealand", insensitive=True)
print(code) # "NZ"
# Search in different language
with translation.override("fr"):
code = countries.by_name("Nouvelle-Zélande")
print(code) # "NZ"
# Regex search (returns set of matching codes)
codes = countries.by_name(r"^New", regex=True)
print(codes) # {"NC", "NZ"} (New Caledonia, New Zealand)
# Check membership
assert "NZ" in countries
assert len(countries) > 0
# Index access (for legacy compatibility)
first_country = countries[0]
print(first_country) # CountryTuple(code='AF', name='Afghanistan')
```
--------------------------------
### Automated Release Commands (Bash)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
Commands to trigger automated patch, minor, or major releases. These commands automate steps like pulling changes, updating translations, bumping versions, building packages, and publishing to PyPI.
```bash
# For a patch release (bug fixes: 7.7.0 -> 7.7.1)
just deploy patch
# For a minor release (new features: 7.7.0 -> 7.8.0)
just deploy minor
# For a major release (breaking changes: 7.7.0 -> 8.0.0)
just deploy major
```
--------------------------------
### Add Django Countries to INSTALLED_APPS
Source: https://github.com/smileychris/django-countries/blob/main/README.md
This Python code snippet shows how to register the 'django_countries' application within your Django project's settings.py file. This step is necessary for Django to recognize and load the application's components.
```python
INSTALLED_APPS = [
# ...
'django_countries',
]
```
--------------------------------
### IOC Code Lookup and HTML Escaping in Django Countries
Source: https://context7.com/smileychris/django-countries/llms.txt
Demonstrates how to look up country information using IOC codes and how to render country names and flags safely in HTML templates using context managers.
```python
from django_countries.fields import Country
# IOC code lookup
olympic_country = Country.country_from_ioc("GER")
print(olympic_country.code) # "DE"
print(olympic_country.name) # "Germany"
invalid = Country.country_from_ioc("INVALID")
print(invalid) # None
# HTML escaping for safe template rendering
from django.utils.safestring import SafeString
country = Country("FR")
with country.escape:
# Properties are HTML-escaped inside this context
safe_name = country.name
safe_flag = country.flag
assert isinstance(safe_name, str)
```
--------------------------------
### Create Django Form with Multiple Country Field
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/multiple.md
Provides an example of creating a Django ModelForm that includes the 'countries' field configured for multiple selections. This allows users to select multiple countries through the form.
```python
from django import forms
from myapp.models import Incident
class IncidentForm(forms.ModelForm):
class Meta:
model = Incident
fields = ['title', 'countries']
```
--------------------------------
### Configure Flag Image URL Template
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/settings.md
Sets the template string used to generate URLs for flag images. Supports placeholders like {code} and {code_upper}. Can be relative to STATIC_URL or an absolute URL.
```python
# Use PNG flags in a subdirectory
COUNTRIES_FLAG_URL = "flags/16x10/{code_upper}.png"
```
```python
# Use absolute URL
COUNTRIES_FLAG_URL = "https://cdn.example.com/flags/{code}.svg"
```
--------------------------------
### Use CountryFilterSet in a function-based view
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/django_filters.md
Shows how to apply a PersonFilterSet within a Django function-based view to filter a queryset of Person objects based on user GET requests. The filtered results are then passed to the template for display.
```python
def person_list(request):
filterset = PersonFilterSet(request.GET, queryset=Person.objects.all())
return render(
request,
"people/list.html",
{"filter": filterset, "object_list": filterset.qs},
)
```
--------------------------------
### GraphQL Schema Definition
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
Defines the root GraphQL schema by combining the defined Query type. This is the entry point for all GraphQL queries.
```python
import graphene
from myapp.queries import Query
schema = graphene.Schema(query=Query)
```
--------------------------------
### Extend Country Object with External Plugins (setup.py)
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/customization.md
Shows how to register an external Python package as a plugin for Django Countries using the 'django_countries.Country' entry point in a setup.py file. This allows adding custom attributes to the Country object.
```python
setup(
...
entry_points={
"django_countries.Country": "phone = django_countries_phone.get_phone"
},
...
)
```
--------------------------------
### Set Countries to Display First
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/settings.md
Defines a list of country codes that should appear at the beginning of the country selection list, before the standard alphabetical order.
```python
# Show US, UK, and Canada first
COUNTRIES_FIRST = ["US", "GB", "CA"]
```
--------------------------------
### Display Country Flag using CSS in Django Templates
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/field.md
Provides an example of how to use the `flag_css` property within Django templates to display country flags using CSS classes. It includes options for different resolutions and accessibility attributes.
```django
```
```django
Normal:
Bigger:
```
```django
```
--------------------------------
### Country Object API - Lightweight Country Data Wrapper
Source: https://context7.com/smileychris/django-countries/llms.txt
Explains the Country object API, a lightweight wrapper for country codes that provides lazy-loaded properties like name, alpha3, numeric code, and Unicode flag. It demonstrates creating Country objects, accessing their properties, and performing comparisons and boolean checks.
```python
from django_countries.fields import Country
# Create Country objects
nz = Country("NZ")
usa = Country("US", flag_url="//cdn.example.com/{code}.png")
spain = Country("ES", str_attr="name")
# Properties
print(nz.code) # "NZ"
print(nz.name) # "New Zealand"
print(nz.alpha3) # "NZL"
print(nz.numeric) # 554
print(nz.unicode_flag) # "🇳🇿"
# String representation controlled by str_attr
print(str(nz)) # "NZ" (default: str_attr="code")
print(str(spain)) # "Spain" (str_attr="name")
# Comparison
assert nz == "NZ"
assert nz != "US"
assert bool(nz) == True
assert bool(Country("")) == False
```
--------------------------------
### Global Settings for Django Countries Configuration
Source: https://context7.com/smileychris/django-countries/llms.txt
Details how to configure country display, filtering, and flag URLs globally via Django's settings.py, including options for flag URL templates, common names, overrides, and country restrictions.
```python
# settings.py
# Flag URL template (relative to STATIC_URL or absolute)
COUNTRIES_FLAG_URL = "flags/{code}.gif" # Default
COUNTRIES_FLAG_URL = "img/flags/{code_upper}.png"
COUNTRIES_FLAG_URL = "https://cdn.example.com/flags/{code}.svg"
# Use friendlier common names
COUNTRIES_COMMON_NAMES = True # Default
# Examples:
# "Bolivia" vs "Bolivia, Plurinational State of"
# "South Korea" vs "Korea (the Republic of)"
# "Taiwan" vs "Taiwan (Province of China)"
# Override specific country names
from django.utils.translation import gettext_lazy as _
COUNTRIES_OVERRIDE = {
"NZ": _("Middle Earth"),
"AU": None, # Exclude Australia entirely
"GB": {"name": _("Britain"), "alpha3": "BRI"}, # Override codes too
}
# Restrict to specific countries only
COUNTRIES_ONLY = {
"US": _("United States"),
"CA": _("Canada"),
"MX": _("Mexico"),
}
# Or just codes (uses default names)
COUNTRIES_ONLY = ["US", "CA", "MX"]
# Show certain countries first in dropdowns
COUNTRIES_FIRST = ["US", "GB", "CA"] # Order matters
COUNTRIES_FIRST_REPEAT = True # Also show in sorted list (default: False)
COUNTRIES_FIRST_BREAK = "---" # Separator after first countries
COUNTRIES_FIRST_SORT = True # Sort first countries alphabetically
# Example combined configuration for US-focused application
COUNTRIES_FLAG_URL = "https://flagcdn.com/w20/{code}.png"
COUNTRIES_COMMON_NAMES = True
COUNTRIES_FIRST = ["US", "CA", "GB", "AU"]
COUNTRIES_FIRST_BREAK = "---"
```
--------------------------------
### DRF OPTIONS Request for Country Choices
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/drf.md
When requesting OPTIONS against a DRF resource, country choices are returned in the response, providing a list of available countries for selection. This leverages DRF's metadata support. Request example shown.
```http
OPTIONS /api/person/ HTTP/1.1
```
--------------------------------
### Query Django Model with Multiple Country Field
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/multiple.md
Demonstrates how to query a Django model that uses the multiple CountryField. Examples include using the '__contains' lookup to find records associated with a specific country code and '__name' for country name matching.
```python
# Find incidents involving New Zealand
>>> Incident.objects.filter(countries__contains='NZ')
# Find incidents involving Australia
>>> Incident.objects.filter(countries__name='Australia')
```
--------------------------------
### Data Regeneration Script (Python)
Source: https://github.com/smileychris/django-countries/blob/main/docs/contributing.md
A Python command to regenerate the `data.py` file from updated country data. This script is run after manually updating the ISO 3166-1 CSV file.
```bash
uv run --group dev python django_countries/data.py
```
--------------------------------
### Get Single Country Object by Code (Django Template Tag)
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/templates.md
Retrieves a `Country` object based on its country code and assigns it to a specified template variable. This allows access to all country properties within the template. It takes the country code as the first argument and the variable name to store the country object as the second.
```django
{% get_country 'COUNTRY_CODE' as variable_name %}
```
--------------------------------
### Python Graphene Mutation for Person Creation
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
This Python code defines a Graphene mutation 'CreatePerson' that handles the creation of a 'Person' object. It takes name, email, and country code as arguments and uses Django's ORM to save the data. Dependencies include 'graphene' and Django models/types.
```python
import graphene
from myapp.models import Person
from myapp.types import PersonType
class CreatePerson(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
email = graphene.String(required=True)
country_code = graphene.String(required=True)
person = graphene.Field(PersonType)
def mutate(self, info, name, email, country_code):
person = Person.objects.create(
name=name,
email=email,
country=country_code
)
return CreatePerson(person=person)
class Mutation(graphene.ObjectType):
create_person = CreatePerson.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
```
--------------------------------
### Country Name Translation and Internationalization
Source: https://context7.com/smileychris/django-countries/llms.txt
This Python code illustrates how to fetch country names in different languages using Django's translation utilities and the `django_countries` library. It shows how to override the active language contextually and how model instances and country iteration respect these translations. It also touches upon fallback mechanisms for renamed countries and marking custom names as translatable.
```python
from django.utils import translation
from django_countries import countries
from myapp.models import Person
# Get country name in different languages
with translation.override("en"):
print(countries.name("DE")) # "Germany"
with translation.override("fr"):
print(countries.name("DE")) # "Allemagne"
with translation.override("es"):
print(countries.name("DE")) # "Alemania"
# Model instances use current active language
person = Person.objects.get(name="Chris")
with translation.override("fr"):
print(person.country.name) # Uses French if available
# Iterating countries respects current language
with translation.override("es"):
for code, name in countries:
print(f"{code}: {name}")
# Returns Spanish names
# Fallback behavior for renamed countries
# If a country was renamed and translation only exists for old name,
# the library automatically falls back to the old name translation
# Marking custom names as translatable
from django.utils.translation import gettext_lazy as _
# In settings.py
COUNTRIES_OVERRIDE = {
"NZ": _("Aotearoa New Zealand"), # Will be translated
}
# Disable i18n for testing (in settings)
USE_I18N = False
# Country names will use English only
```
--------------------------------
### Add Separator Label for 'First' Countries
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/settings.md
Specifies a string to be displayed as a visual separator between the `COUNTRIES_FIRST` list and the main alphabetically sorted country list. Useful for UI clarity.
```python
COUNTRIES_FIRST = ["US", "GB", "CA"]
COUNTRIES_FIRST_BREAK = "───────────" # Adds visual separator
```
--------------------------------
### Extend Country Object with External Plugins (pyproject.toml)
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/customization.md
Illustrates how to define an external plugin for Django Countries using the 'django_countries.Country' entry point in a pyproject.toml file. This enables the addition of new attributes to the Country object through external packages.
```toml
[project.entry-points."django_countries.Country"]
phone = "django_countries_phone:get_phone"
```
--------------------------------
### GraphQL Query Resolvers for Person and Company
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
Implements GraphQL query resolvers for 'person', 'people', 'company', and 'companies'. These resolvers fetch data from the Django database using the defined object types.
```python
import graphene
from myapp.models import Person, Company
from myapp.types import PersonType, CompanyType
class Query(graphene.ObjectType):
person = graphene.Field(PersonType, id=graphene.Int(required=True))
people = graphene.List(PersonType)
company = graphene.Field(CompanyType, id=graphene.Int(required=True))
companies = graphene.List(CompanyType)
def resolve_person(self, info, id):
return Person.objects.get(pk=id)
def resolve_people(self, info):
return Person.objects.all()
def resolve_company(self, info, id):
return Company.objects.get(pk=id)
def resolve_companies(self, info):
return Company.objects.all()
```
--------------------------------
### Django ORM Lookups for Country Filtering
Source: https://context7.com/smileychris/django-countries/llms.txt
Illustrates advanced Django ORM lookups provided by Django Countries for filtering database records based on country fields. Supports filtering by country code, country name (case-sensitive and insensitive), pattern matching, and regex. Also covers handling multiple country fields, ordering, and value extraction.
```python
from myapp.models import Person, Company
from django.db.models import F
# Standard lookups (by code)
people = Person.objects.filter(country="NZ")
people = Person.objects.filter(country__in=["NZ", "AU", "GB"])
people = Person.objects.exclude(country="")
# Name-based lookups
people = Person.objects.filter(country__name="New Zealand")
people = Person.objects.filter(country__iname="new zealand") # Case-insensitive
# Pattern matching on names
people = Person.objects.filter(country__contains="island")
people = Person.objects.filter(country__icontains="ISLAND")
people = Person.objects.filter(country__startswith="New")
people = Person.objects.filter(country__istartswith="new")
people = Person.objects.filter(country__endswith="Zealand")
people = Person.objects.filter(country__iendswith="zealand")
# Regex on names
people = Person.objects.filter(country__regex=r"^New|^United")
people = Person.objects.filter(country__iregex=r"kingdom|republic")
# Multiple country fields
companies = Company.objects.filter(
operating_countries__contains="US" # Has US in the list
)
# Ordering
people = Person.objects.order_by("country") # Orders by code
people = Person.objects.annotate(
country_name=F("country")
).order_by("country_name") # Also by code
# Select related still works normally
people = Person.objects.select_related("organization").filter(country="NZ")
# Values queries
country_codes = Person.objects.values_list("country", flat=True)
# Returns: ["NZ", "US", "GB", ...]
```
--------------------------------
### Sort 'First' Countries Alphabetically
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/settings.md
Determines whether the countries listed in `COUNTRIES_FIRST` should be sorted alphabetically among themselves. If True, they will be ordered alphabetically.
```python
COUNTRIES_FIRST = ["US", "GB", "CA"]
COUNTRIES_FIRST_SORT = True # Will display as: CA, GB, US
```
--------------------------------
### Repeat 'First' Countries in Main List
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/settings.md
Controls whether countries specified in `COUNTRIES_FIRST` should also appear in the main, alphabetically sorted list. Set to True to include them twice.
```python
COUNTRIES_FIRST = ["US", "GB", "CA"]
COUNTRIES_FIRST_REPEAT = True # Countries appear both at top and in main list
```
--------------------------------
### Accessing External Plugin Attributes (Python REPL)
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/customization.md
Demonstrates how to access custom attributes added to a Country object via external plugins in a Python REPL. This shows the practical usage after setting up an entry point.
```python
>>> from django_countries import countries
>>> country = countries['US']
>>> country.phone # Calls get_phone(country)
'+1'
```
--------------------------------
### Set Countries to Display First (Python)
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/customization.md
Use the `COUNTRIES_FIRST` setting with a list of country codes to ensure these countries appear at the beginning of the selection list, before the alphanumerically sorted countries.
```python
COUNTRIES_FIRST = ["US", "GB", "CA"]
```
--------------------------------
### Allow First Countries to Repeat in List (Python)
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/customization.md
Set `COUNTRIES_FIRST_REPEAT` to `True` to allow the countries listed in `COUNTRIES_FIRST` to also appear in the main alphanumerically sorted list.
```python
COUNTRIES_FIRST = ["US", "GB", "CA"]
COUNTRIES_FIRST_REPEAT = True
```
--------------------------------
### Override Country Names: Customize Display Names (Python)
Source: https://github.com/smileychris/django-countries/blob/main/docs/iso3166-formatting.md
Allows customization of the display names for specific territories. This is useful for aligning country names with specific branding, legal requirements, or user interface preferences. The value `None` can be used to effectively remove a territory from the list.
```python
COUNTRIES_OVERRIDE = {
'TW': 'Taiwan, China',
'HK': 'Hong Kong SAR, China',
'MO': 'Macao SAR, China',
}
```
```python
COUNTRIES_OVERRIDE = {
'TW': None, # Removes Taiwan from list
}
```
--------------------------------
### Customize Individual CountryField with Custom Countries Class
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/settings.md
Demonstrates how to create a custom `Countries` class to apply specific settings (like `only`, `first`, `first_break`) to an individual `CountryField` instance, rather than project-wide.
```python
from django.utils.translation import gettext_lazy as _
from django_countries import Countries
from django_countries.fields import CountryField
class EUCountries(Countries):
only = [
"AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR",
"DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL",
"PL", "PT", "RO", "SK", "SI", "ES", "SE",
]
first = ["DE", "FR", "IT"]
first_break = "───────────"
class Product(models.Model):
name = models.CharField(max_length=100)
country = CountryField(countries=EUCountries)
```
--------------------------------
### Django Template Tags for Country Data
Source: https://context7.com/smileychris/django-countries/llms.txt
Utilize Django template tags to fetch and display country information, including names, codes, flags, and Unicode flags. This also covers iterating through a list of all countries for dropdown menus and using CSS sprites for flag display. Assumes the 'countries' template tag library is loaded.
```django
{% load countries %}
{# Get a Country object from code #}
{% get_country 'NZ' as new_zealand %}
Country: {{ new_zealand.name }}
Code: {{ new_zealand.code }}
Flag:
Unicode: {{ new_zealand.unicode_flag }}
{# Using with model instance #}
{{ person.name }}
From: {{ person.country.name }}
Flag: {{ person.country.unicode_flag }}
{# Get all countries for custom dropdown #}
{% get_countries as country_list %}
{# Flag CSS sprite (requires flags/sprite.css) #}
```
--------------------------------
### Configure Django URLs for Country API Endpoints
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/drf.md
Sets up URL patterns for the Person and Company viewsets using Django's DefaultRouter and include. This requires django.urls and myapp.views.
```python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import PersonViewSet, CompanyViewSet
router = DefaultRouter()
router.register(r'persons', PersonViewSet)
router.register(r'companies', CompanyViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
```
--------------------------------
### Create Person Mutation
Source: https://github.com/smileychris/django-countries/blob/main/docs/integrations/graphql.md
Allows the creation of a new person record, including their name, email, and a country code. This mutation enables associating a person with a specific country upon creation.
```APIDOC
## POST /mutations/createPerson
### Description
Creates a new person record with the provided details, including a country code.
### Method
POST
### Endpoint
`/mutations/createPerson`
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **name** (string) - Required - The name of the person.
- **email** (string) - Required - The email address of the person.
- **country_code** (string) - Required - The ISO code of the person's country.
### Request Example
```graphql
mutation {
createPerson(name: "John", email: "john@example.com", countryCode: "US") {
person {
id
name
country {
code
name
}
}
}
}
```
### Response
#### Success Response (200)
- **data** (object)
- **createPerson** (object)
- **person** (object)
- **id** (integer) - The unique identifier of the created person.
- **name** (string) - The name of the person.
- **country** (object)
- **code** (string) - The ISO code of the person's country.
- **name** (string) - The name of the person's country.
#### Response Example
```json
{
"data": {
"createPerson": {
"person": {
"id": 1,
"name": "John",
"country": {
"code": "US",
"name": "United States"
}
}
}
}
}
```
```
--------------------------------
### Display Individual Country Flag Image (Django Template)
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/templates.md
Renders an individual country's flag as an `` element. It uses the `get_country` tag to retrieve the country object and accesses its `flag` property for the image source URL. The `static` template tag is also loaded to handle static file paths.
```django
{% load countries %}
{% load static %}
{% get_country 'US' as country %}
```
--------------------------------
### Load Django Countries Template Tags
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/templates.md
Loads the Django Countries template tag library, making its functions available for use in the current template. This is a prerequisite for using other `countries` tags.
```django
{% load countries %}
```
--------------------------------
### Customize Country Data with Dictionaries (Python)
Source: https://github.com/smileychris/django-countries/blob/main/docs/advanced/customization.md
Demonstrates how to override or define country data using complex dictionaries for settings like 'names', 'alpha3', 'numeric', and 'ioc_code'. This allows for granular control over country information.
```python
from django.utils.translation import gettext_lazy as _
COUNTRIES_OVERRIDE = {
"US": {
"names": [
_("United States of America"),
_("USA"),
_("America"),
],
},
}
COUNTRIES_OVERRIDE = {
"XX": {
"names": [_("Custom Country")],
"alpha3": "XXX",
},
}
COUNTRIES_OVERRIDE = {
"XX": {
"names": [_("Custom Country")],
"numeric": 900,
},
}
COUNTRIES_OVERRIDE = {
"XX": {
"names": [_("Custom Country")],
"ioc_code": "XXX",
},
}
from django.utils.translation import gettext_lazy as _
COUNTRIES_OVERRIDE = {
"NZ": {
"names": [_("New Zealand"), _("Aotearoa")],
"alpha3": "NZL",
"numeric": 554,
"ioc_code": "NZL",
},
"XX": {
"names": [_("Custom Country")],
"alpha3": "XXX",
"numeric": 900,
"ioc_code": "",
},
}
```
--------------------------------
### Build Custom Country Select with Pre-selection (Django Template)
Source: https://github.com/smileychris/django-countries/blob/main/docs/usage/templates.md
Constructs a custom HTML select dropdown for countries, including an option for 'Select a country'. It allows for pre-selecting an option based on a `selected_country` variable and displays the Unicode flag alongside the country name. This leverages `get_countries` and conditional logic.
```django
{% load countries %}
{% get_countries as countries %}
```