开发者

how to make dynamically generated forms with one to many relationships in django

开发者 https://www.devze.com 2023-01-05 00:20 出处:网络
i am trying to write a quiz system to learn django where users can add quizes to the system. my models look like

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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消