How to add a Money field in Django?

PythonServer Side ProgrammingProgramming

Sometimes, we may have to add money-related data in a website, like salary, fees or income. Django provides an integer field but many a time, it doesn't work like we want. So, for handling money field, we can use a third-package library that will add the money field to our model.

Make a project and an app, I named it "MoneyFieldDemo" and "myapp".

Set the basic things like urls and INSTALLED_APPS.

And yes, install a library −

pip install django-money

Add the following line in

INSTALLED_APPS+= ["djmoney"]


In app's,, add the following lines −

from django.urls import path
from . import views

urlpatterns = [
   path('', views.home,name="home"),

Here, we simply define our url endpoint which will render the html.

In the templates folder's home.html, add −

<!DOCTYPE html>
      <form action="/" method="post">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Submit">

It is the html file that we are going to render as the frontend.

In, add the following −

from django.db import models
from djmoney.models.fields import MoneyField

# Create your models here.
class Data(models.Model):
   salary = MoneyField(max_digits=14, decimal_places=2, defa
ult_currency='USD') #This is money field

Here, we created a model which has two value employee names and his salary in USD.

In, add the following −

from django.shortcuts import render
from django import forms
from .models import Data
# Create your views here.

class SalaryForm(forms.ModelForm):
   class Meta:
def home(request):
   if request.method=='POST':
         if form.is_valid():


   return render(request,'home.html',{'form':form})

There is nothing fancy in We made a form in it and then just render it and also handle post request.


Published on 25-Aug-2021 12:34:55