2013-06-18 83 views
2

我有一個帶有m2m字段的模型給OtherModel。設置Django ModelChoiceField的初始值

class OtherModel(models.Model)  
    name = models.CharField(max_length=100, null=True) 

class Model(models.Model) 
    name = models.CharField(max_length=100, null=True) 
    otherModel = models.ManyToManyField(OtherModel) 

對於模型我使用一個普通的FormSet()。對於otherModel我用formset_factory()類

我只希望允許從OtherModel數據庫中選擇數據,所以我在OtherModel與此代碼更改CharField名字命名的ModelChoiceField:

def otherModel_formset(self, patientenID): 

    class OtherModelForm(ModelForm): 
     name= ModelChoiceField(queryset=OtherModel.objects.all()) 

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


     class Meta: 
      model = OtherModel 
      fields = ['name'] 

    return formset_factory(form=OtherModelForm, max_num=10) 

我可在M2M領域保存所選的名字,但在重裝他們選擇什麼

exampel:

<select id=some_id" name="some_name"> 
    <option value="1"> HAWAII </option> 
    <option value="2"> ALASKA</option> 
</select> 

在exampel ALASKA在提交和重載應該處於一種這個所選:

<select id=some_id" name="some_name"> 
    <option value="1"> HAWAII </option> 
    <option value="2" **selected="selected"**> ALASKA</option> 
</select> 

,但這一立場在HTML內容:

<select id=some_id" name="some_name"> 
    <option value="1"> HAWAII </option> 
    <option value="2"> ALASKA</option> 
</select> 

有人知道解決辦法?

+0

您需要發佈相關代碼:您的視圖在哪裏?您的視圖需要將綁定的表單(form(request.POST)發送回模板。 –

回答

4

的問題是使用request.POSTinitial={'name': 'ALASKA'}在一起。發生這種情況是因爲request.POST的值始終會覆蓋參數「initial」的值,所以我們必須將其分開。我的解決方案是使用這種方式。

views.py

if request.method == "POST": 
    form=OtherModelForm(request.POST) 
else: 
    form=OtherModelForm() 

forms.py

class OtherModelForm(ModelForm): 
    name= ModelChoiceField(queryset=OtherModel.objects.all(), initial={'name': 'ALASKA'}) 

---------- ----------或

views.py

if request.method == "POST": 
    form=OtherModelForm(request.POST) 
else: 
    form=OtherModelForm(initial={'name': 'ALASKA'}) 

In forms.py

class OtherModelForm(ModelForm): 
    name= ModelChoiceField(queryset=OtherModel.objects.all()) 
1

你應該有你的觀點的東西,看起來是沿着線:

form=OtherModelForm(request.POST, initial={'name': 'ALASKA'}) 
0

我有如下代碼:

otherModel = OtherModel.objects.all() 
otherModelFormSet = otherModel_formset(id) 
otherModelList = otherModel.values('id', 'name') 
inProgressOtherModel = otherModelFormSet(None, initial=otherModelList, prefix='otherModel')