Django Money

3.6.0 · active · verified Mon Apr 13

Django Money is a little Django app that integrates the `py-moneyed` library to add robust support for money and currency fields in Django models and forms. It ensures accurate handling of monetary values, currency conversions, and formatting. The current version, 3.6.0, supports modern Django and Python versions and is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a `MoneyField` in a Django model, create instances with `Money` objects, and perform basic queries. It also highlights the required `INSTALLED_APPS` entry and the use of localization settings for proper display. The template tag `money_localize` is conceptually shown for front-end rendering.

import os
import django
from django.conf import settings
from django.db import models

settings.configure(
    INSTALLED_APPS=[
        'djmoney',
        'tests',
    ],
    DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
    DEFAULT_CURRENCY='USD',
    USE_L10N=True, # Enable localization for formatting
)
django.setup()

from djmoney.models.fields import MoneyField
from djmoney.money import Money

class BankAccount(models.Model):
    balance = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
    # It's also possible to have a nullable MoneyField:
    # money = MoneyField(max_digits=10, decimal_places=2, null=True, default_currency=None)

    def __str__(self):
        return f"{self.balance} - {self.pk}"

# Run migrations (simplified for quickstart)
with open(os.devnull, 'w') as f:
    import sys
    _stdout = sys.stdout
    sys.stdout = f
    try:
        from django.core.management import call_command
        call_command('makemigrations', 'tests', verbosity=0, interactive=False)
        call_command('migrate', verbosity=0, interactive=False)
    finally:
        sys.stdout = _stdout

# Create an account
account = BankAccount.objects.create(balance=Money(100, 'USD'))
print(f"Created account: {account}")

# Querying
expensive_accounts = BankAccount.objects.filter(balance__gt=Money(50, 'USD'))
print(f"Accounts with balance > $50: {list(expensive_accounts)}")

# Accessing amount and currency separately
print(f"Account balance amount: {account.balance.amount}")
print(f"Account balance currency: {account.balance.currency}")

# Example of template tag usage (conceptual, as this is a console quickstart)
# In a Django template:
# {% load djmoney %}
# <p>Current balance: {{ account.balance|money_localize }}</p>

view raw JSON →