我正在尝试使用 m2m 中间表保存表单。实现多选字段表单时出现此错误:
Cannot assign "[Option: Option1]": "StateOption.partoption" must be a "Option" instance.
但是,如果我注释掉表单将保存但一次只能保存 1 个选项。我希望能够有一个清单并让用户选择多个选项。
我正在使用这个:Django m2m form save " through " table 作为参考,但必须承认我不太了解它,尤其是 for 循环部分。
我的问题是:如何保存表格?我明白为什么我会收到实例错误,但我不知道如何解决它。此外,下面的 for 循环可能是错误的。任何有关如何修复 for 循环的建议将不胜感激。似乎这将允许我保存多项选择。
模型.py
class Disease(models.Model):
disease = models.CharField(max_length=300, verbose_name="disease")
class Option(models.Model):
relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
option = models.CharField(max_length=300, verbose_name="treatment Options")
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)
relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')
表格.py
class StateOptionForm(forms.ModelForm):
partoption = forms.ModelMultipleChoiceField(queryset=Option.objects.all(), required=True, widget=forms.CheckboxSelectMultiple)
#if I comment the line above out, then my selection will save but only 1 at at time. There are multiple options for a 'state' and I'd like to capture it all at once
class Meta:
model = StateOption
exclude = ['parttstate', 'relevantoutcome']
视图.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 = StateOptionForm(request.POST, request.FILES)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
for state in request.POST.getlist('relevantoption'): #don't really understand this part and I'm probably not implementing this right
option = StateOption.objects.create(partstate=state, partoption=profile)
return HttpResponseRedirect(reverse('state', kwargs={'disease_id':disease_id}))
else:
form = StateOptionForm()
模板
<form class="option_form" action="{% url "diseasestateoption" disease.pk state.pk %}" method="post">{% csrf_token %}
{{ disease }}
{{ state }}
{{option}}
我之前在这里发布过类似的问题,但没有得到答案。我是 django 和 stackoverflow 的新手,所以任何帮助将不胜感激。
编辑
我能够在没有中间表并使用 save_m2m() 的情况下实现这一点,但是,我将需要一个中间表用于我的程序的下一部分......如果我可以先解决这部分。