2016-01-13 46 views
0

我有一個模型在一個字段中存儲不同類型的數據(離散值或連續值)(在另一個字段中存儲類型)。在該模型的ModelForm中,我有一個ChoiceField來選擇數據項,並使用ChoiceField或DecimalField來設置項目的值。在django管理員表單中響應用戶操作?

當我創建表單時,我根據項目的類型設置值的字段。但是,如果我選擇不同類型的項目,我想立即更改值字段以匹配。

當窗體仍處於活動狀態時,即在用戶更改字段值但未單擊「提交」按鈕時,我無法找到任何方式來響應更改。有沒有辦法做到這一點?最好留在服務器上的Python,而不是瀏覽器端在javascript中編碼。

ChoiceField的選項取自模型,因此無法在任何地方進行硬編碼。

下面是一些代碼:

class FooProperty (models.Model): 
    foo  = models.ForeignKey ('foos.Foo') 
    prop = models.ForeignKey ('foos.FooProperty') 
    value = models.DecimalField (max_digits=15, decimal_places=6) # is an EnumValue id in the case of discrete values. 

class FooPropertyForm (forms.ModelForm): 
    class Meta: 
     model = FooProperty 
     fields = ['prop', 'value'] 

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

     if hasattr (self.instance, 'prop'): 
      kind = self.instance.prop.units.kind 
      if kind.id != 1: 
       values = [(v.id, v.name) for v in EnumValues.objects.filter (kind=kind.id)] 
       self.fields ['value'] = forms.ChoiceField (choices=values, required=True) 
       self.initial['value'] = int(self.instance.value) # using initial= above doesn't work. 
      else: 
       # keep the default field. 
       pass 

回答

0

我具有存儲不同類型的值(STR,INT,小數,等),根據其類型相似的多態模型。

你能澄清一下你的問題嗎?你說「如果我選擇一個不同類型的項目」。你的意思是改變瀏覽器或代碼中的表單域?

我假設你是指前者。 如果沒有來自客戶端的某種異步通信,則無法響應Python中的實時表單更改。

在我的應用程序,這是一個兩步驟的過程:

  1. 來選擇一個類型
  2. 在客戶端的用戶,該類型字段的改變處理器觸發調用來獲取類型 - 特定的表單字段。有一個單獨的Django視圖,它用一組特定的字段和邏輯來實例化一個單獨的表單。

var $kind = $('#kind'); 
 

 
$kind.on('change', fetchFormFieldsForKind); 
 

 
function fetchFormFieldsForKind() { 
 
    var kind = $kind.val(); 
 
    $.get(
 
    "{% url 'form_fields_for_kind' %}?kind=" + $kind.val(), 
 

 
    function (response) { 
 
     newFieldsHtml = response.newFieldsHtml || ''; 
 

 
     // Replace all following sibling form fields with the new ones 
 
     // (each field is wrapped by a div with Bootstrap class form-group) 
 
     $kind.closest('.form-group').find('~ .form-group').remove(); 
 
     $kind.after(newFieldsHtml); 
 

 
     // or replace the whole form with a rendered ModelForm 
 
    } 
 
); 
 
}

對於完整性,即Django的看法會是這個樣子:

def form_fields_for_kind(request, kind): 
    """ 
    Given the string 'kind', return a rendered form that contains 
    any type-specific fields. 
    """ 
    form = YourForm(kind=kind) 
    content = form.as_p() 
    return HttpResponse(content, 'text/html') 
相關問題