Computer >> Computer tutorials >  >> Programming >> Python

How to add a Money field in Django?


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 settings.py

INSTALLED_APPS+= ["djmoney"]

Example

In app's, urls.py, 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>
<html>
   <head>
      <title>
         TUT
      </title>
   </head>
   <body>
      <h2>Hi</h2>
      <form action="/" method="post">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Submit">
      </form>
   </body>
</html>

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

In models.py, add the following −

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

# Create your models here.
class Data(models.Model):
   Name=models.CharField(max_length=100)
   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 view.py, 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:
      model=Data
      fields="__all__"
def home(request):
   if request.method=='POST':
      form=SalaryForm(request.POST)
         if form.is_valid():
            form.save()

   else:
      form=SalaryForm()

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

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

Output

How to add a Money field in Django?