2014-11-05 75 views
2

我試圖做到以下幾點:如何在django的模型中爲DecimalField創建一個IntegerField?

class AmountInfoForm(forms.ModelForm): 

    amount = forms.IntegerField() 

    class Meta: 
     model = Customer 
     fields = ('amount',) 

對於我的模型領域:

class Customer(models.Model): 
    amount = models.DecimalField(max_digits=6, decimal_places=2, null=True) 

這是爲了讓顯示在我的文字輸入值是圓的,而不是顯示小數。

問題是,小數位仍然顯示。

它只接受例如60作爲輸入值。但是,當它顯示該字段的表單實例時,它顯示60.00 我在做什麼錯了?

+0

@madzohan你在說什麼解決方案是? – Atma 2014-11-05 19:01:40

+0

忘了它,我是不留神)指定自定義的部件爲這個領域,並在該部件覆蓋渲染方法 – madzohan 2014-11-05 19:48:59

+0

@madzohan你知道一個例子或它在文檔中的位置嗎?從幾次嘗試看來,整數字段沒有渲染方法。 – Atma 2014-11-05 21:42:07

回答

2

1) Django的字段沒有被插件DJANGO,默認爲窗口小部件和DecimalFieldIntegerFieldTextInput

而從this note您的聲明將覆蓋amount字段的默認行爲。但是存儲的數據在Decimal類型不int所以如果你想代表它在int你應該做的水木清華這樣的:

int(Decimal()) 

或閱讀Decimal docs和設置自定義舍入。

2)在這個步驟中,您需要不便指定您的自定義渲染,所以有變化,你如何能做到這一點的數量(在這一刻我還記得他們兩個人):

2.1)簡單的一個 - 覆蓋的ModelForm INIT初始數據:如果您需要在花式小部件的定製表示你可以覆蓋)

class AmountInfoForm(forms.ModelForm): 
    class Meta: 
     model = Customer 
     fields = ('amount',) 

    def __init__(self, *args, **kwargs): 
     super(AmountInfoForm, self).__init__(*args, **kwargs) 

     amount_initial = self.initial.get('amount') 
     if amount_initial: 
      self.initial['amount'] = int(amount_initial) 

2.2TextInputlook at the source),並指定我t in your class Metadocs

class YourCustomWidget(TextInput): 
    def render(self, name, value, attrs=None): 
     if value is None: 
      value = '' 
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) 
     if value != '': 
      # Only add the 'value' attribute if a value is non-empty. 
      custom_value = int(value) 
      final_attrs['value'] = force_text(self._format_value(custom_value)) 

     # here you can customise output html 
     return format_html('<input{0} />', flatatt(final_attrs)) 

class AmountInfoForm(forms.ModelForm): 
    class Meta: 
     model = Customer 
     fields = ('amount',) 
     widgets = { 
      'amount': YourCustomWidget(), 
     } 
+0

這就是它!!!!! 2.1例子運行得很順暢! – Atma 2014-11-06 15:09:50

相關問題