How can I set default_currency= "INR" in settings.py file because its use many times in project?

364 Views Asked by At

I want to save MoneyField details in setting.py file so I can use it every places where I use MoneyField I want to save this..

MoneyField(max_digits=10, decimal_places=2, default_currency='INR', null=False, default=0.0)

How can save it in settings.py

2

There are 2 best solutions below

0
willeM_ Van Onsem On

Django uses a setting named DEFAULT_CURRENCY to set the currency, the default is 'XYZ'. Indeed, if we look at the source code [GitHub], we see:

from ..settings import CURRENCY_CHOICES, DECIMAL_PLACES, DEFAULT_CURRENCY

# …

class MoneyField(models.DecimalField):
    # …

    def __init__(
        self,
        # ...,
        default_currency=DEFAULT_CURRENCY,
        # …
    ):
        # …
    
    # …

You thus can set the DEFAULT_CURRENCY in the settings.py to:

# settings.py

# …

DEFAULT_CURRENCY = 'INR'

# …

and the omit the default_currency='INR' parameters when you create MoneyFields.

0
Abhyudai On

You can probably make use of functools.partial to do this.

from functools import partial

from django.db import models

MyMoneyField = partial(
    models.DecimalField,
    default='INR',
    ...
)

Now you can use this in the form:

class MyModel(models.Model):
    amount = MyMoneyField()

In case, you want this to be configurable via your settings, just set DEFAULT_CURRENCY to INR in your settings.py, and then use it in the form:

from django.conf import settings

MyMoneyField = partial(
    models.DecimalField,
    default=settings.DEFAULT_CURRENCY,
    ...
)

partial also allows use to replace the previously filled argument. For example:

class AnotherModel(models.Model):
    new_amount = MyMoneyField(current='USD')