I'm trying to use multiple custom fields in my project. For example CurrencyField
. I want to give it a default arguments like verbose_name
- "mena" etc.
Django raises error:
kwargs['verbose_name'] = kwargs['verbose_name'] or 'Mena'
I guess it's because I sometimes use verbose_name
as a positional argument. How can I make it "universal"?
class CurrencyChoices(models.TextChoices):
EUR = 'EUR'
CHF = 'CHF'
CZK = 'CZK'
DKK = 'DKK'
GBP = 'GBP'
HRK = 'HRK'
HUF = 'HUF'
PLN = 'PLN'
RON = 'RON'
SEK = 'SEK'
USD = 'USD'
class CurrencyField(models.CharField):
def __init__(self, *args, **kwargs):
kwargs['verbose_name'] = kwargs['verbose_name'] or 'Mena'
kwargs['max_length'] = 5
kwargs['choices'] = CurrencyChoices.choices
super().__init__(*args, **kwargs)
If you do not specify the verbose_name
in the constructor, it will raise a KeyError
, you can work with .get(…)
instead, or perhaps even better: .setdefault(…)
:
class CurrencyField(models.CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('verbose_name', 'Mena')
kwargs['max_length'] = 5
kwargs['choices'] = CurrencyChoices.choices
super().__init__(*args, **kwargs)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.