如何在Django中创建动态生成的一对多关系表单
我正在尝试写一个测验系统来学习Django,让用户可以往系统里添加测验。我的模型看起来是这样的:
from google.appengine.ext import db
class Quiz(db.Model):
title=db.StringProperty(required=True)
created_by=db.UserProperty()
date_created=db.DateTimeProperty(auto_now_add=True)
class Question(db.Model):
question=db.StringProperty(required=True)
answer_1=db.StringProperty(required=True)
answer_2=db.StringProperty(required=True)
answer_3=db.StringProperty(required=True)
correct_answer=db.StringProperty(choices=['1','2','3','4'])
quiz=db.ReferenceProperty(Quiz)
我想知道怎么创建表单、视图和模板,让用户能看到一个页面来创建测验。到目前为止,我想出了这个。
视图:from google.appengine.ext.db.djangoforms import ModelForm
from django.shortcuts import render_to_response
from models import Question,Quiz
from django.newforms import Form
def create_quiz(request):
return render_to_response('index.html',{'xquestion':QuestionForm(),'xquiz':QuizForm()})
class QuestionForm(ModelForm):
class Meta:
model=Question
exclude=['quiz']
class QuizForm(ModelForm):
class Meta:
model=Quiz
exclude=['created_by']
模板(index.html)
Please Enter the Questions
<form action="" method='post'>
{{xquiz.as_table}}
{{xquestion.as_table}}
<input type='submit'>
</form>
我怎么才能在测验表单中添加多个问题呢?
1 个回答
-1
到目前为止,一切都很好,如果没有错误的话,你应该能看到一个正常工作的界面,上面有表单。
现在你只需要在 create_quiz
这个视图中处理提交的数据。
if request.method == 'POST':
xquiz = QuizForm(request.POST)
quiz_instance = xquiz.save(commit=False)
quiz_instance.created_by = request.user
quiz_instance.save()
xquestion = QuestionForm(request.POST)
question_instance = xquestion.save(commit=False)
question_instance.quiz = quiz_instance
question_instance.save()
更新:如果你想要多个问题的表单,那你需要了解一下表单集,具体可以查看这个链接:http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1