how to make dynamically generated forms with one t

2019-09-14 05:59发布

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)

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']

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?

1条回答
混吃等死
2楼-- · 2019-09-14 06:44

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

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

查看更多
登录 后发表回答