Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add a Money field in Django?
Django's default IntegerField and DecimalField don't handle currency properly for financial applications. The django-money library provides a MoneyField that handles currency symbols, decimal precision, and multi-currency support.
Installation and Setup
First, install the django-money package ?
pip install django-money
Add it to your Django project's settings.py ?
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djmoney', # Add this line
'myapp', # Your app name
]
Creating the Model
Create a model with a MoneyField in models.py ?
from django.db import models
from djmoney.models.fields import MoneyField
class Employee(models.Model):
name = models.CharField(max_length=100)
salary = MoneyField(
max_digits=14,
decimal_places=2,
default_currency='USD'
)
def __str__(self):
return f"{self.name} - {self.salary}"
URL Configuration
Set up URLs in your app's urls.py ?
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
]
Views and Forms
Create a form and view to handle the MoneyField in views.py ?
from django.shortcuts import render, redirect
from django import forms
from .models import Employee
class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = "__all__"
def home(request):
if request.method == 'POST':
form = EmployeeForm(request.POST)
if form.is_valid():
employee = form.save()
return redirect('home')
else:
form = EmployeeForm()
employees = Employee.objects.all()
return render(request, 'home.html', {
'form': form,
'employees': employees
})
HTML Template
Create a template to display the form and saved data in templates/home.html ?
<!DOCTYPE html>
<html>
<head>
<title>Django Money Field Demo</title>
</head>
<body>
<h2>Employee Salary Form</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Employee</button>
</form>
<h3>Employee List</h3>
{% for employee in employees %}
<p>{{ employee.name }}: {{ employee.salary }}</p>
{% empty %}
<p>No employees added yet.</p>
{% endfor %}
</body>
</html>
Key Features
The MoneyField provides several advantages ?
- Currency Support: Handles multiple currencies (USD, EUR, etc.)
- Decimal Precision: Proper handling of decimal places
- Database Storage: Stores amount and currency separately
- Form Rendering: Automatically renders currency selection
Migration
Don't forget to create and run migrations ?
python manage.py makemigrations python manage.py migrate
Conclusion
The django-money library provides a robust MoneyField that handles currency, decimal precision, and form rendering automatically. This is much more reliable than using Django's basic number fields for financial data.
