django - 来自 CharField 的具有默认参数的自定义字段
我正在尝试在我的项目中使用多个自定义字段。例如CurrencyField
。 我想给它一个默认参数,如 verbose_name - "mena" 等。Django
引发错误:
kwargs['verbose_name'] = kwargs['verbose_name'] or 'Mena'
我想这是因为我有时使用 verbose_name 作为位置参数。我怎样才能使它“通用”?
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您没有在构造函数中指定 verbose_name ,它将引发一个 KeyError ,您可以使用 .get(…) 来代替,或者也许更好:
.setdefault(…)
:If you do not specify the
verbose_name
in the constructor, it will raise aKeyError
, you can work with.get(…)
instead, or perhaps even better:.setdefault(…)
: