0
我試圖使用m2m結構保存多選擇複選框表單,但我的值未保存到數據庫。使用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)
更新 可能是不需要的中間表用於該用途的情況下,但是當我添加更多的com時會需要它這個問題很複雜。有沒有辦法用中間表將這個表單保存到數據庫中?
那麼,StateOption模型是不需要的。除非我錯過了一些東西,ORM應該爲你創建連接表。 –
你是對的。如果我擺脫了StateOption並在我的StateOptionForm中使用model = State,那麼表單仍然不會保存在爲我創建的表ORM中。我只創建了一箇中間表,以便減少從2到1創建的新表。關於爲什麼它不保存的任何想法? – nlr25
編輯上面的代碼並刪除StateOption模型,然後讓我們看看。 –