使用m2m关系保存表单而不保存到数据库

时间:2013-08-21 20:14:19

标签: python django

我正在尝试使用m2m结构保存多选复选框表单,但我的值未保存到数据库中。

我有一个州和选项。状态可以有多个选项,选项可以有多个状态。实际上,我想为每个状态保存多个选项,然后将连接保存在中间StateOption表中。没有产生错误但是当我检查我的数据库时,没有保存任何内容。

此外,如果您发现我设置数据库结构的方式有任何问题,请随时发表评论。我是数据库和django的新手。

models.py

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

class State(models.Model):
   state = models.CharField(max_length=255)
   relevantdisease = models.ForeignKey(Disease)
   relevantoption = models.ManyToManyField(Option, blank=True, through='StateOption')

#intermediate table may not be needed
class StateOption(models.Model):
   state_table = models.ForeignKey(State)
   option_table = models.ForeignKey(Option)

forms.py

class StateOptionForm(forms.ModelForm):
    option_choices = forms.ModelMultipleChoiceField(queryset=Option.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)

    class Meta:
       model = State #StateOption if I use the intermediate table
       exclude = ['state_table', 'option_table']

views.py

def stateoption(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 = StateOptionForm(request.POST, instance=state)

        if form.is_valid():
           profile = form.save(commit=False)
           profile.user = request.user
           profile.save()    #this and the line below is probably where the problem is
           form.save_m2m()   


           #stateoption = StateOption.objects.create(state_table=state, option_table=profile)   <--produces an error saying that the instance needs to be Option

           return HttpResponseRedirect(reverse('success'))

    else:
        form = StateOptionForm(instance=state)


    context = {'state': state, 'disease':disease, 'option': form }
    return render(request, "stateoption.html", context)

更新 此用例可能不需要中间表,但是当我为此问题添加更多复杂性时,将需要它。有没有办法使用中间表将此表单保存到数据库?

1 个答案:

答案 0 :(得分:0)

通过更改:

来解决它
class StateOptionForm(forms.ModelForm):
    option_choices = forms.ModelMultipleChoiceField(queryset=Option.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)

to class StateOptionForm(forms.ModelForm):
    relevantoption = forms.ModelMultipleChoiceField(queryset=Option.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)

这样它就匹配了我的模特。