表单不通过中间表保存到数据库

时间:2013-08-27 17:25:19

标签: django

我有一个未保存到数据库的自定义表单。我没有得到任何错误,但值不保存到数据库。有什么想法吗?

views.py

def diseasestateoption(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":
        form = UpdateStateWithOptionsForm(request.POST, instance=state)

        if form.is_valid(): 
           for option_id in request.POST.getlist('options'):
               state_option = StateOption.objects.create(partstate=state, partoption_id=int(option_id))
               state_option.save()
        return HttpResponseRedirect(reverse('success'))

else:
    form = UpdateStateWithOptionsForm(instance=state)

models.py

class Option(models.Model):
        relevantdisease = models.ForeignKey(Disease)
        option = models.CharField(max_length=300)

class State(models.Model):
       state = models.CharField(max_length=300, verbose_name='state')
       relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
       relevantoption = models.ManyToManyField(Option, through='StateOption')

class StateOption(models.Model):
       parttstate = models.ForeignKey(State)
       partoption = models.ForeignKey(Option)

forms.py

class UpdateStateWithOptionsForm(forms.ModelForm):
    class Meta:
       model = State
       exclude = ['state', 'relevantdisease']

    def __init__(self, *args, **kwargs):
       super(UpdateStateWithOptionsForm, self).__init__(*args, **kwargs)
       self.fields['relevantoption']=forms.ModelMultipleChoiceField(queryset=Option.objects.all(),required=True, widget=forms.CheckboxSelectMultiple)

1 个答案:

答案 0 :(得分:1)

我认为问题在于从POST获取选项,使用 -

request.POST.getlist('relevantoption')

代替

request.POST.getlist('options')

除此之外,为什么在这里使用form for single multiple choice field,即使你也在修改选择而不使用form.save。