views:

50

answers:

2

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?

A: 

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

Ashok
@Ashok but a quiz does not just contains of one Question.What i am looking for is a way to have multiple question in the Quiz form
Bunny Rabbit
@Ashok does formset work with appengine too ?
Bunny Rabbit
just updated my answer regarding the same, you can get multiple forms with formsets, http://docs.djangoproject.com/en/dev/topics/forms/formsets/
Ashok
not tested but it should work
Ashok