[英]how to make dynamically generated forms with one to many relationships in django
i am trying to write a quiz system to learn django where users can add quizes to the system. 我试图编写一个测验系统来学习django,用户可以在其中添加测验。 my models look like 我的模特看起来像
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)
my question is how do create Form+views+templates to present user with a page to create quizes so far i have come up with this. 我的问题是如何创建Form + views + templates来向用户展示一个页面来创建测验,到目前为止,我已经提出了这一点。 Views: 观看次数:
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']
template(index.html) 模板(index.html)
Please Enter the Questions
<form action="" method='post'>
{{xquiz.as_table}}
{{xquestion.as_table}}
<input type='submit'>
</form>
How can i have multiple Questions in the quiz form? 我如何在测验表格中有多个问题?
so far so good, as of now you should be having a working view with the forms rendered, if there are no errors. 到目前为止一切顺利,到目前为止,如果没有错误,您应该已经有了一个工作视图,其中显示了表单。
now you just need to handle the post data in create_quiz
view 现在您只需要在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()
update: if you are looking for multiple question forms then you need to look at formsets, http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1 更新:如果您要查找多个问题表单,则需要查看表单集, http ://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.