我正在使用django提出問題應用程序,我允許用戶向網站添加問題,併爲每個問題定義了幾個可選答案提出問題的用戶。我想在下拉框中顯示可選答案。但我一直從我的模型得到一個錯誤,說選項一沒有定義。是否有可能將表單值存儲在django的下拉列表中
選擇模式
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
CHOICES = (
(option_one,option_one),
(option_two,option_two),
)
user_choice = models.CharField(
max_length=200,
choices=CHOICES,
default=Yes,
)
votes = models.IntegerField(default=0)
def __str__(self):
return self.user_choice
視圖
def create_poll(request):
if request.method == 'POST':
form = CreatePollForm(request.POST)
if form.is_valid():
question = form.cleaned_data['question']
option_one = form.cleaned_data['option_one']
option_two = form.cleaned_data['option_two']
print option_one
q = Question.objects.create(question_text=question)
o = Choice.objects.create(question=q, option_one=option_one,option_two=option_two)
q.save()
o.save
form = CreatePollForm()
return render(request, 'polls/createPolls_form.html', {'form':form})
form = CreatePollForm()
return render(request,'polls/createPolls_form.html',{'form':form})
forms.py
class CreatePollForm(forms.Form):
question = forms.CharField(max_length=100)
option_one = forms.CharField(max_length=100)
option_two = forms.CharField(max_length=100)
如果你有'choices'參數,並且你試圖提供自定義值,那麼你的表單驗證將失敗。 –