2010-10-11 50 views
2

內優雅降級我有一個類似於以下(簡化爲簡潔起見)的一種形式:處理Django的形式

PRICING_PATTERN = r'(?:^\$?(?P<flat_price>\d+|\d?\.\d\d)$)|(?:^(?P<percent_off>\d+)\s*\%\s*off$)' 
class ItemForm(forms.Form): 
    pricing = forms.RegexField(
     label='Pricing', 
     regex=PRICING_PATTERN 
    ) 

    pricing_type = forms.CharField(
     label='Deal type', 
     widget=forms.RadioSelect(
      choices=(
       ('flat_price','Flat price'), 
       ('percent_off','Percentage off'), 
      ), 
      attrs={'style': 'display: none;'}) 
     ), 
    ) 

    pricing_flat_price = forms.DecimalField(
     label='Flat price', 
     max_digits=5, 
     decimal_places=2, 
     widget=forms.TextInput(attrs={'style': 'display: none;'}) 
    ) 

    pricing_percent_off = forms.IntegerField(
     label='Percent off', 
     required=False, 
     min_value=0, 
     max_value=100, 
     widget=forms.TextInput(attrs={'style': 'display: none;'}) 
    ) 

最初,優雅降級的目的,只有定價是可見的。如果用戶啓用了javascript,我會隱藏定價並使定價類型可見。現在,在pricing_type無線電選擇上,我使pricing_flat_costpricing_percent_off可見。這使得用戶界面更加精確和用戶友好。

我的問題:我應該如何去編碼該數字從哪裏取從值邏輯---在RegexField或pricing_flat_pricepricing_percent_off領域?我是否應該在ItemForm中創建一個函數計算出來並返回正確的值?

或者有人可以建議更清潔的方法嗎?

回答