如何在Django Model中实现类似CountryField()的ISO-4217货币代码下拉列表
Hey there! I totally get the frustration of trying to replicate that smooth CountryField experience for currencies— I’ve been down that road before. Let’s break down a couple of solid solutions that’ll get you that clean "CODE-Currency Name" dropdown you’re after.
Option 1: Custom Model Field with pycountry (Recommended)
This is the closest match to how django-countries works, since we’ll leverage a trusted library (pycountry) that maintains up-to-date ISO-4217 data, so you don’t have to manually curate or update the currency list.
Step 1: Install pycountry
First, grab the library that handles all the ISO currency data:
pip install pycountry
Step 2: Create the Custom Currency Field
Add this to your app’s models.py:
from django.db import models import pycountry class CurrencyField(models.CharField): def __init__(self, *args, **kwargs): # Generate currency choices in the "CODE-Name" format currency_choices = [] for currency in pycountry.currencies: # Handle edge cases where some entries might lack a name if hasattr(currency, 'name'): display_label = f"{currency.alpha_3}-{currency.name}" currency_choices.append((currency.alpha_3, display_label)) # Sort choices alphabetically by the display label for usability currency_choices.sort(key=lambda x: x[1]) # Set default parameters for the field kwargs.setdefault('max_length', 3) # ISO-4217 codes are 3 characters kwargs.setdefault('choices', currency_choices) super().__init__(*args, **kwargs)
Step 3: Use the Field in Your Model
Now you can use this field just like CountryField:
class YourModel(models.Model): # Other fields... preferred_currency = CurrencyField()
This will automatically render a dropdown in the Django admin and any forms using this model, with options like AFN-Afghani, EUR-Euro, USD-Dollar— exactly what you want.
Option 2: Manual Choice List (For Static Use Cases)
If you don’t want to rely on a third-party library, you can manually define a list of ISO-4217 choices. Note: This requires manual updates if ISO ever changes currency codes, so it’s not ideal for long-term use.
# Define this in your models.py or a separate constants file CURRENCY_CHOICES = [ ('AFN', 'AFN-Afghani'), ('EUR', 'EUR-Euro'), ('USD', 'USD-Dollar'), # Add all other ISO-4217 codes and their names here ] class YourModel(models.Model): preferred_currency = models.CharField(max_length=3, choices=CURRENCY_CHOICES)
Option 3: Use django-currencies (Pre-built Field)
There’s a Django library specifically for currency handling that includes a ready-made field. While it might need a tiny tweak for your desired label format, it’s a quick option:
- Install the library:
pip install django-currencies
Add
'currencies'to yourINSTALLED_APPSinsettings.py.Use the field in your model:
from currencies.fields import CurrencyField class YourModel(models.Model): preferred_currency = CurrencyField()
If the default label format doesn’t match "CODE-Name", you can subclass the field to adjust the choices (similar to Option 1).
Why django-international Might Have Confused You
That library focuses more on broader internationalization tasks like translation, timezone handling, and locale settings— it’s not designed specifically for creating currency dropdowns, which is why it felt unclear. The options above are far more targeted for your use case.
内容的提问来源于stack exchange,提问作者Viji Lakshmi

