如何在django中创建一个与多个关系的动态生成的表单 [英] how to make dynamically generated forms with one to many relationships in django
问题描述
我正在尝试编写一个测验系统来学习django,用户可以在系统中添加quizes。
我的模型看起来像
i am trying to write a quiz system to learn django where users can add quizes to the system. 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)
我的问题是如何创建Form +视图+模板来向用户显示一个页面来创建$ c
到目前为止我已经提出了这一点。
视图:
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. 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']
模板(index.html)
template(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.
现在您只需要处理 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()
更新:如果您正在寻找多个问题表单,那么您需要查看formets, http://docs.dja ngoproject.com/en/dev/topics/forms/modelforms/#id1
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
这篇关于如何在django中创建一个与多个关系的动态生成的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!