2015-09-20 25 views
1

我是django的新手。我需要根據用戶在表單中選擇的單選按鈕將條件下拉列表放到我的Web應用程序中。這個想法是,基於用戶的單選按鈕選擇,應該在表單上填充另一個下拉列表。此下拉列表將從數據庫中檢索的值列表中。從此下拉菜單中選擇的最終值將通過按下不同的按鈕來完成主要操作。請建議如何做到這一點。一個例子或鏈接肯定會有所幫助。由於Django - 如何在數據庫的模板中添加條件下拉菜單

我的示例代碼

<script> 
    function my_radio_select() { 
    var1 = document.getElementById("radio1"); 
    var2 = document.getElementById("radio2"); 
    var3 = document.getElementById("radio3"); 
    if (var1.checked === true) { 
     window.location.href = "A.html"; 
    } 
    else if(var2.checked === true) { 
     window.location.href = "A.html"; 
     document.myform.action = "A.html"; 
    } 
    else if(var3.checked === true) { 
     window.location.href = "A.html"; 
    } 
} 
    </script> 

    <br> 
    <br> 
    <br> 
    <input type="radio" id="radio1" name="project_type" value=0 checked onclick="my_radio_select();"> 
    <label>Projects I own</label> 
    <br> 
    <input type="radio" id="radio2" name="project_type" value=1 onclick="my_radio_select();"> 
    <label>Projects I manage</label> 
    <br> 
    <input type="radio" id="radio3" name="project_type" value=1 onclick="my_radio_select();"> 
    <label>Projects I can edit</label> 
{% endblock %} 

class MyProjForm(ModelForm): 
    existing_projs = CSProj.objects.all() 
    choices_int = tuple((p.name, p.name) for p in existing_projs) 
    #tech = forms.ChoiceField(label='Existing Projects' ,widget=forms.Select(attrs={'class':'form-control'}),choices=choices_int,required=True) 
    tech = forms.ChoiceField(label='Existing Projects' ,widget=forms.Select(attrs={'class':'form-control'}),choices=choices_int,required=False) 

    class Meta: 
     model = CSProj 
     fields = ['name','user_workspace', 'compiler_path','ccs_path','tdk_path'] 
     exclude = ('name','user_workspace', 'compiler_path','ccs_path','tdk_path') 

    def __init__(self, *args, **kwargs): 
     if 'user' in kwargs: 
      user = kwargs.pop('user') 

     super(MyProjForm, self).__init__(*args, **kwargs) 
     ### Done to refresh choices as soon as it is added 
     existing_projs = CSProj.objects.filter(owner_id=user) 
     choices_int = tuple((p.name, p.name) for p in existing_projs) 
     self.fields['tech'].choices=choices_int 

回答

0

如果你想要做的所有的東西無需重新加載,你需要使用AJAX頁面。 Django只會爲你提供表單。

1)渲染表單中的所有必填字段(或兩種形式)。

2)隱藏只有當單選按鈕被選中時纔會出現的字段(或表單)(使用JS,jQuery)。

3)顯示隱藏的東西,並使用ajax獲取必要的值,因爲單選按鈕被選中。

+0

嗨,謝謝你的回覆。我對這個領域很陌生。我沒有想法。如果你能說出一些肯定會有所幫助的例子。感謝您回覆 – user3364086

+0

@ user3364086只有在您滿意答案後才接受答案!否則他們只會離開它.. –

+0

請顯示你的表格,標記你想要出現的字段,如果單選按鈕被選中 - 我會給你一個例子。 – chem1st

相關問題