在Django项目中,我使用的是django-money包。
当表单处于编辑模式时,如果它们为空,我需要即时修改其Money字段的初始货币值:
from djmoney.models.fields import MoneyField
DEFAULT_CURRENCY = 'EUR'
CURRENCIES_CHOICES = [
('EUR', 'Euro (EUR)'),
('USD', 'US Dollar (USD)'),
('GBP', 'Pound Sterling (GBP)')]
class ExampleModel(models.Model):
description = models.TextField(blank=True)
total_charged = MoneyField(max_digits=22,
decimal_places=7,
default_currency=DEFAULT_CURRENCY,
currency_choices=CURRENCIES_CHOICES,
null=True, blank=True)
class FormExampleEdit(forms.ModelForm):
class Meta:
model = ExampleModel
fields = ['description', 'total_charged']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.initial.get(total_charged, None) is None:
self.fields['total_charged'].initial = [None, 'USD']
MoneyField由两个字段(金额和货币)组成。
当使用FormExampleEdit
实例实例化ExampleModel
时(编辑模式),如果total_charged
字段为None,则其初始货币值将设置为'EUR',即{在模型字段中选择的{1}}。
在某些情况下,这种货币可能取决于其他因素,因此当我使用ExampleModel的实例化实例时,我会检查实例是否将default_currency
设置为total_charged
,在这种情况下,我会进行处理表单字段的初始值,以将其货币设置为其他货币,例如“ USD”。
如果我检查表单实例,则所有内容均应正常工作,但是以某种方式呈现表单时,未选择美元,则默认选择了欧元货币。
我在创建模式下做了类似的操作(我没有在模型实例中通过),在这种情况下它可以工作。不知道是什么原因造成的。