You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django Model中实现类似CountryField()的ISO-4217货币代码下拉列表

Solution for ISO-4217 Currency Dropdown Like django-countries' CountryField

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.

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:

  1. Install the library:
pip install django-currencies
  1. Add 'currencies' to your INSTALLED_APPS in settings.py.

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:28:14