所以我有這些模型Question
,Answer
,和UserAnswer
組成一個測驗。我面臨的問題是製作一個可以通過這些模型進行驗證的表單。我有一個如何做的想法,但它不工作。Django測驗 - 用戶生成
class QAForm(forms.Form):
answers = forms.ChoiceField(label='Question is this', choices=[('Answer1','Answer1'),('Answer2','Answer2')], widget=forms.RadioSelect())
這適用於1表格,而不是數千。我將如何修改此代碼,以便用戶將所有用戶生成的問題作爲表單答案,並可以提供自己的答案。
我有這樣的(它的工作原理,但我知道這是不是一個好的做法):
def questions(request):
queryset = Questions.objects.all()
if request.method =='POST':
a = request.POST['answer']
answer = Answer.objects.get(answer=a)
importance = request.POST['importance']
q = request.POST['question']
question = Questions.objects.get(id=q)
try:
user_answer = UserAnswers.objects.get(owner=request.user, question=question)
user_answer.answer = answer
user_answer.importance = importance
user_answer.save()
except:
user_answer = UserAnswers(owner=request.user, question=question, answer=answer, importance=importance)
user_answer.save()
else:
try:
current = UserAnswers.objects.all().filter(owner=request.user)
except:
current = ''
return render_to_response("questions/base.html", locals(), context_instance=RequestContext(request))
我的模型:
class Answer(models.Model):
answer = models.CharField(max_length=120)
question = models.ForeignKey('Questions', null=True, blank=True)
def __unicode__(self):
return self.answer
IMPORTANCE = (
('Irrelevant', 'Irrelevant'),
('A Little Important', 'A Little Important'),
('Somewhat Important', 'Somewhat Important'),
('Very Important', 'Very Important'),
('Mandatory', 'Mandatory'),
)
class Questions(models.Model):
owner = models.ForeignKey(User)
question = models.CharField(max_length=300)
importance = models.CharField(max_length=120, choices=IMPORTANCE, null=True, blank=True)
updated = models.DateTimeField(auto_now=False, auto_now_add=True)
timestamp = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.question
class Meta:
verbose_name ='Question'
verbose_name_plural ='Questions'
class UserAnswers(models.Model):
owner = models.ForeignKey(User)
question = models.ForeignKey(Questions)
answer = models.ForeignKey(Answer)
importance = models.CharField(max_length=120, choices=IMPORTANCE)
def __unicode__(self):
return str(self.owner) + " " + str(self.answer) + " " + str(self.importance)
[你嘗試過什麼?](http://whathaveyoutried.com) – arulmr 2013-02-16 10:21:48
@arulmr只是增加了我的意見,告訴你如何我現在有它的工作。 – jmitchel3 2013-02-16 10:24:00
用戶生成的部分工作正常。這是表單的渲染不能正常工作。 – jmitchel3 2013-02-16 10:29:47