m2m 構造を使用して複数選択チェック ボックス フォームを保存しようとしていますが、値がデータベースに保存されません。
State と Options があります。状態は複数のオプションを持つことができ、オプションは複数の状態を持つことができます。実際には、状態ごとに複数のオプションを保存してから、接続を中間の StateOption テーブルに保存します。エラーは発生しませんが、データベースを確認すると、何も保存されていません。
また、データベース構造のセットアップ方法に問題がある場合は、お気軽にコメントしてください。私はデータベースとジャンゴが初めてです。
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)
フォーム.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']
ビュー.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)
更新 このユースケースでは中間テーブルはおそらく必要ありませんが、この問題をさらに複雑にするにつれて必要になります。このフォームを中間テーブルを使用してデータベースに保存する方法はありますか?