0
我是相對較新的Django,並試圖創建一個頁面,在那裏我問問題,並允許用戶給出兩個答案。所以我想顯示一個問題列表,以及下面兩個猜測的字段。我試圖使用表單,但是我無法保存或驗證從這些表單中獲得的數據。 下面是我的相關代碼。在頁面上的幾種形式
從models.py:
class Subject(models.Model):
subject = models.FloatField(verbose_name='ID')
class SubjectForm(forms.Form):
subject = forms.FloatField()
class General(models.Model):
question = models.CharField(max_length=400)
answer = models.FloatField()
class Guess(models.Model):
general = models.ForeignKey(General)
subject = models.ForeignKey(Subject)
lower = models.FloatField('lower boundary')
upper = models.FloatField('upper boundary')
class GuessForm(forms.Form):
lower = forms.FloatField()
upper = forms.FloatField()
從views.py:
def questions(request):
if request.method == 'POST': # If answers were submitted
for question in all_questions:
form = GuessForm()
if form.is_valid():
lower = request.POST.get('lower','')
upper = request.POST.get('upper','')
new_guess = Guess(pk = 'question',
subject = subject,
lower = lower,
upper = upper)
new_quess.save()
return HttpResponseRedirect('/general_knowledge/questions/thanks/')
else:
form = GuessForm()
csrfContext = RequestContext(request,{'form': form})
return render_to_response('general_knowledge/question_form.html',
{'all_questions': all_questions},
context_instance=RequestContext(request))
從模板
{% for question in all_questions %}
<form action="" method="post">{% csrf_token %}
<ol>
<p><LI> {{ question.question }}.</p>
<label for="lower">Lower boundary:</label><input type="text" name="lower">
{{ form.lower.errors }}
<label for="upper">Upper boundary: </label><input type="text" name="upper">
{{ form.upper.errors }}
</ol>
</form>
{% endfor %}
<input type="submit" value="Submit" />
儘管接受,我不明白這是如何回答問題的書面。這個問題關於如何在Django中驗證和保存表單數據。在客戶端的jQuery驗證將是一個很好的補充,但這不是問題的關鍵。 – 2012-02-28 15:41:06
@ PaulD.Waite如果這最終幫助了她 - 她可能不需要更多。這比0的答案好,如果你有更正確的答案,我會很高興,如果你寫。 – ParPar 2012-03-05 08:48:03
非常真實,非常真實。 – 2012-03-05 12:14:01