实例化一个modelForms MultiSelectCheckBox小部件

时间:2013-09-18 22:39:22

标签: django django-forms

我正在使用ModelForms小部件ModelMultipleChoiceField。我有两个问题:

  1. 我的SelectOptionForStateForm处理选项的复选框小部件呈现了我数据库中stateoption表中的现有选择。如何查看该表中的现有记录?在我的views.py中,我只传递了diseasestate对象,这些对象没有查看stateoption表。

  2. 如何实例化我的SelectOutcomeForOptionForm,以便我的数据库中的stateoptionoutcome表中也预先选择了我的治疗结果复选框?

  3. forms.py

    class SelectOptionForStateForm(forms.ModelForm):
        class Meta:
           model = State
           exclude = ['state', 'relevantdisease']
    
        def __init__(self, *args, **kwargs):
           disease=kwargs.pop('disease', None)
           super(SelectOptionForStateForm, self).__init__(*args, **kwargs)
           self.fields['relevantoption']=forms.ModelMultipleChoiceField(queryset=Option.objects.filter(relevantdisease_id=disease),required=True, widget=forms.CheckboxSelectMultiple)
           self.fields['relevantoption'].label="Treatment Options"
    
    class SelectOutcomeForOptionForm(forms.ModelForm):
        class Meta:
           model = StateOption
           exclude = ['partstate', 'partoption']
    
        def __init__(self, *args, **kwargs):
           disease=kwargs.pop('disease', None)
           super(SelectOutcomeForOptionForm, self).__init__(*args, **kwargs)
           self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.filter(relevantdisease_id=disease),required=True, widget=forms.CheckboxSelectMultiple)
           self.fields['relevantoutcome'].label="Treatment Outcomes"
    

    views.py

    def stateoptionoutcome(request, disease_id, state_id):
    
        state = get_object_or_404(State, pk=state_id)
        disease = get_object_or_404(Disease, pk=disease_id)
    
        if request.method == "POST":
            optionForm = SelectOptionForStateForm(request.POST, disease=disease, instance=state)
            outcomeForm = SelectOutcomeForOptionForm(request.POST, disease=disease, instance=state)
    
            if optionForm.is_valid() and outcomeForm.is_valid(): 
               #Deletes state objects so there are no duplicate options in the database
               try:
                   state_option = StateOption.objects.filter(partstate=state).delete()
    
               except StateOption.DoesNotExist:
                   state_option = None
    
               #Saves user options to database
               for option_id in request.POST.getlist('relevantoption'):
                   state_option = StateOption.objects.create(partstate=state, partoption_id=int(option_id))
    
                   #Deletes stateoption objects found in StateOptionOutcome 
                   try:
                       state_option_outcome = StateOptionOutcome.objects.filter(stateoption=state_option).delete()
    
                   except StateOptionOutcome.DoesNotExist:
                       state_option_outcome = None
    
                   #Saves user outcomes to database
                   for outcome_id in request.POST.getlist('relevantoutcome'):
                       state_option_outcome = StateOptionOutcome.objects.create(stateoption=state_option, relevantoutcome_id=int(outcome_id))
    
               return HttpResponseRedirect(reverse('diseasestateoptionlist', kwargs={'disease_id':disease_id, 'state_id':state_id}))
    

    models.py

    class State(models.Model):
           state = models.CharField(max_length=255)
           relevantdisease = models.ForeignKey(Disease)
           relevantoption = models.ManyToManyField(Option, through='StateOption')
    
    class StateOption(models.Model):
           partstate = models.ForeignKey(State)
           partoption = models.ForeignKey(Option)
           relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')
    
    class StateOptionOutcome(models.Model):
           stateoption = models.ForeignKey(StateOption)
           relevantoutcome = models.ForeignKey(Outcome)
           outcomevalue = models.CharField(max_length=20)
    

1 个答案:

答案 0 :(得分:0)

我能够用这个来解决#2:

stateoptionlist = StateOption.objects.filter(partstate_id=state_id) 
if not stateoptionlist:
    stateoption = state 
else: 
    stateoption = stateoptionlist[0]

如果state返回一个空列表(即stateoptionlist表中没有记录),则传递StateOption实例。更新每个SelectOutcomeForOptionForm的views.py,我的实例将替换为stateoption

我很想知道是否有更有效的方法来解决#2。