DJango How to build a formset for a Quiz?












3















I'm working on a quiz application that needs to display a quiz to be taken
My models .py looks like this



from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin

#######################
#Quiz Structure Models#
#######################

class Quiz(models.Model):
name = models.CharField(max_length = 255)
creation = models.DateField(auto_now_add=True)
creator = models.ForeignKey(User)

def __unicode__ (self):
return self.name

def possible(self):
total = 0
for question in self.question_set.all():
question.save()
total += question.value
return total



class Question(models.Model):
question = models.CharField(max_length = 255)
quiz = models.ForeignKey(Quiz)
creator = models.ForeignKey(User)
creation = models.DateField(auto_now_add = True)
#objective = TODO: include standards linking in later versions
value = models.IntegerField(default = 1)

def __unicode__(self):
return self.question

class Answer(models.Model):
answer = models.CharField(max_length = 255)
question = models.ForeignKey(Question)
is_correct = models.BooleanField(default = False)
#Creator is tied to the quiz


##########
#Attempts#
##########
class QuizAttempt(models.Model):
student = models.ForeignKey(User)
quiz = models.ForeignKey(Quiz)
date = models.DateField(auto_now_add = True)
#Score Method (similar to possible in Quiz


class QuestionAttempt(models.Model):
attempt = models.ForeignKey(QuizAttempt)
question = models.ForeignKey(Question)
response = models.ForeignKey(Answer)


#######
#Admin#
#######

class QuestionInline(admin.StackedInline):
model = Question
extra = 2


class AnswerInline(admin.StackedInline):
model = Answer
extra = 2


class QuizAdmin(admin.ModelAdmin):
list_display = ('name', 'creator', 'creation', 'possible',)
search_fields = ('name', 'creator')
inlines = [QuestionInline]

admin.site.register(Quiz, QuizAdmin)

class QuestionAdmin(admin.ModelAdmin):
inlines = [AnswerInline]
search_fields = ('question', 'quiz', 'value',)
list_display = ('question', 'quiz', 'value',)

admin.site.register(Question, QuestionAdmin)


I'm trying to build a form or form-set that will let me have a form for a quiz attempt that contains all of the questions so it looks something like this, and will let me get that back in a view to save a student's attempt at a quiz.




  1. Question 1

    • Option a

    • ect




So far it looks like my best solution is to build a formset out of these models, but I'm not sure how to specify my choices to limit it to answers associated with the current question, or how to get the right formset in a view.










share|improve this question

























  • As a thought, would it be better to put each question on a page, and just pass the quiz_attempt along?

    – TicViking
    Mar 24 '11 at 18:26
















3















I'm working on a quiz application that needs to display a quiz to be taken
My models .py looks like this



from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin

#######################
#Quiz Structure Models#
#######################

class Quiz(models.Model):
name = models.CharField(max_length = 255)
creation = models.DateField(auto_now_add=True)
creator = models.ForeignKey(User)

def __unicode__ (self):
return self.name

def possible(self):
total = 0
for question in self.question_set.all():
question.save()
total += question.value
return total



class Question(models.Model):
question = models.CharField(max_length = 255)
quiz = models.ForeignKey(Quiz)
creator = models.ForeignKey(User)
creation = models.DateField(auto_now_add = True)
#objective = TODO: include standards linking in later versions
value = models.IntegerField(default = 1)

def __unicode__(self):
return self.question

class Answer(models.Model):
answer = models.CharField(max_length = 255)
question = models.ForeignKey(Question)
is_correct = models.BooleanField(default = False)
#Creator is tied to the quiz


##########
#Attempts#
##########
class QuizAttempt(models.Model):
student = models.ForeignKey(User)
quiz = models.ForeignKey(Quiz)
date = models.DateField(auto_now_add = True)
#Score Method (similar to possible in Quiz


class QuestionAttempt(models.Model):
attempt = models.ForeignKey(QuizAttempt)
question = models.ForeignKey(Question)
response = models.ForeignKey(Answer)


#######
#Admin#
#######

class QuestionInline(admin.StackedInline):
model = Question
extra = 2


class AnswerInline(admin.StackedInline):
model = Answer
extra = 2


class QuizAdmin(admin.ModelAdmin):
list_display = ('name', 'creator', 'creation', 'possible',)
search_fields = ('name', 'creator')
inlines = [QuestionInline]

admin.site.register(Quiz, QuizAdmin)

class QuestionAdmin(admin.ModelAdmin):
inlines = [AnswerInline]
search_fields = ('question', 'quiz', 'value',)
list_display = ('question', 'quiz', 'value',)

admin.site.register(Question, QuestionAdmin)


I'm trying to build a form or form-set that will let me have a form for a quiz attempt that contains all of the questions so it looks something like this, and will let me get that back in a view to save a student's attempt at a quiz.




  1. Question 1

    • Option a

    • ect




So far it looks like my best solution is to build a formset out of these models, but I'm not sure how to specify my choices to limit it to answers associated with the current question, or how to get the right formset in a view.










share|improve this question

























  • As a thought, would it be better to put each question on a page, and just pass the quiz_attempt along?

    – TicViking
    Mar 24 '11 at 18:26














3












3








3


4






I'm working on a quiz application that needs to display a quiz to be taken
My models .py looks like this



from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin

#######################
#Quiz Structure Models#
#######################

class Quiz(models.Model):
name = models.CharField(max_length = 255)
creation = models.DateField(auto_now_add=True)
creator = models.ForeignKey(User)

def __unicode__ (self):
return self.name

def possible(self):
total = 0
for question in self.question_set.all():
question.save()
total += question.value
return total



class Question(models.Model):
question = models.CharField(max_length = 255)
quiz = models.ForeignKey(Quiz)
creator = models.ForeignKey(User)
creation = models.DateField(auto_now_add = True)
#objective = TODO: include standards linking in later versions
value = models.IntegerField(default = 1)

def __unicode__(self):
return self.question

class Answer(models.Model):
answer = models.CharField(max_length = 255)
question = models.ForeignKey(Question)
is_correct = models.BooleanField(default = False)
#Creator is tied to the quiz


##########
#Attempts#
##########
class QuizAttempt(models.Model):
student = models.ForeignKey(User)
quiz = models.ForeignKey(Quiz)
date = models.DateField(auto_now_add = True)
#Score Method (similar to possible in Quiz


class QuestionAttempt(models.Model):
attempt = models.ForeignKey(QuizAttempt)
question = models.ForeignKey(Question)
response = models.ForeignKey(Answer)


#######
#Admin#
#######

class QuestionInline(admin.StackedInline):
model = Question
extra = 2


class AnswerInline(admin.StackedInline):
model = Answer
extra = 2


class QuizAdmin(admin.ModelAdmin):
list_display = ('name', 'creator', 'creation', 'possible',)
search_fields = ('name', 'creator')
inlines = [QuestionInline]

admin.site.register(Quiz, QuizAdmin)

class QuestionAdmin(admin.ModelAdmin):
inlines = [AnswerInline]
search_fields = ('question', 'quiz', 'value',)
list_display = ('question', 'quiz', 'value',)

admin.site.register(Question, QuestionAdmin)


I'm trying to build a form or form-set that will let me have a form for a quiz attempt that contains all of the questions so it looks something like this, and will let me get that back in a view to save a student's attempt at a quiz.




  1. Question 1

    • Option a

    • ect




So far it looks like my best solution is to build a formset out of these models, but I'm not sure how to specify my choices to limit it to answers associated with the current question, or how to get the right formset in a view.










share|improve this question
















I'm working on a quiz application that needs to display a quiz to be taken
My models .py looks like this



from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin

#######################
#Quiz Structure Models#
#######################

class Quiz(models.Model):
name = models.CharField(max_length = 255)
creation = models.DateField(auto_now_add=True)
creator = models.ForeignKey(User)

def __unicode__ (self):
return self.name

def possible(self):
total = 0
for question in self.question_set.all():
question.save()
total += question.value
return total



class Question(models.Model):
question = models.CharField(max_length = 255)
quiz = models.ForeignKey(Quiz)
creator = models.ForeignKey(User)
creation = models.DateField(auto_now_add = True)
#objective = TODO: include standards linking in later versions
value = models.IntegerField(default = 1)

def __unicode__(self):
return self.question

class Answer(models.Model):
answer = models.CharField(max_length = 255)
question = models.ForeignKey(Question)
is_correct = models.BooleanField(default = False)
#Creator is tied to the quiz


##########
#Attempts#
##########
class QuizAttempt(models.Model):
student = models.ForeignKey(User)
quiz = models.ForeignKey(Quiz)
date = models.DateField(auto_now_add = True)
#Score Method (similar to possible in Quiz


class QuestionAttempt(models.Model):
attempt = models.ForeignKey(QuizAttempt)
question = models.ForeignKey(Question)
response = models.ForeignKey(Answer)


#######
#Admin#
#######

class QuestionInline(admin.StackedInline):
model = Question
extra = 2


class AnswerInline(admin.StackedInline):
model = Answer
extra = 2


class QuizAdmin(admin.ModelAdmin):
list_display = ('name', 'creator', 'creation', 'possible',)
search_fields = ('name', 'creator')
inlines = [QuestionInline]

admin.site.register(Quiz, QuizAdmin)

class QuestionAdmin(admin.ModelAdmin):
inlines = [AnswerInline]
search_fields = ('question', 'quiz', 'value',)
list_display = ('question', 'quiz', 'value',)

admin.site.register(Question, QuestionAdmin)


I'm trying to build a form or form-set that will let me have a form for a quiz attempt that contains all of the questions so it looks something like this, and will let me get that back in a view to save a student's attempt at a quiz.




  1. Question 1

    • Option a

    • ect




So far it looks like my best solution is to build a formset out of these models, but I'm not sure how to specify my choices to limit it to answers associated with the current question, or how to get the right formset in a view.







python django django-forms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 '11 at 18:31







TicViking

















asked Mar 24 '11 at 18:15









TicVikingTicViking

146210




146210













  • As a thought, would it be better to put each question on a page, and just pass the quiz_attempt along?

    – TicViking
    Mar 24 '11 at 18:26



















  • As a thought, would it be better to put each question on a page, and just pass the quiz_attempt along?

    – TicViking
    Mar 24 '11 at 18:26

















As a thought, would it be better to put each question on a page, and just pass the quiz_attempt along?

– TicViking
Mar 24 '11 at 18:26





As a thought, would it be better to put each question on a page, and just pass the quiz_attempt along?

– TicViking
Mar 24 '11 at 18:26












2 Answers
2






active

oldest

votes


















4














If I am understanding your question correctly, you'll probably want to create a custom Form at execute time, and many custom Fields. I would expect something along the lines of:



class QuizForm(forms.Form):
def __init__(self, data, questions, *args, **kwargs):
self.questions = questions
for question in questions:
field_name = "question_%d" % question.pk
choices =
for answer in question.answer_set().all():
choices.append((answer.pk, answer.answer,))
## May need to pass some initial data, etc:
field = forms.ChoiceField(label=question.question, required=True,
choices=choices, widget=forms.RadioSelect)
return super(QuizForm, self).__init__(data, *args, **kwargs)
def save(self):
## Loop back through the question/answer fields and manually
## update the Attempt instance before returning it.


It will likely take additional tweaking to make this work through the admin interface, but this should give you a good start for constructing the form itself at execution time.



Your view would probably look something like:



# Assuming something like:  /quiz/69/ with "69" being the quiz PK.
def render_quiz(request, quiz_id):
quiz = get_object_or_404(Quiz, quiz_id)
form = QuizForm(questions=quiz.question_set.all())
if request.method == "POST":
form = QuizForm(request.POST, questions=quiz.question_set.all())
if form.is_valid(): ## Will only ensure the option exists, not correctness.
attempt = form.save()
return redirect(attempt)
return render_to_response('quiz.html', {"form": form})





share|improve this answer


























  • How can I be sure I'd get the same form back when I receive the post data?

    – TicViking
    Mar 24 '11 at 20:20













  • Forgot to include the view code. Updated. There is a race condition that exists if the Questions are updated between the time the Form is rendered and the time the answers are submitted. This should, however, show up as a question that was not answered (or that the answer doesn't exist, etc), and take the user back to the new form.

    – Jack M.
    Mar 24 '11 at 20:31











  • Thanks for the added explanation!

    – TicViking
    Mar 24 '11 at 21:46



















1














This is a rough idea of how it should work.



# define a form
class QuestionForm(forms.Form):
id = forms.IntegerField(widget=forms.HiddenInput) # make it hidden- i know, not very elegant
question = forms.CharField()
answer = forms.CharField()

# views.py
def display(request):
quiz = Quiz.objects.get(creator=request.user) # or some definition of quiz
questions = quiz.question_set.all().values('id','question') # to get question text

# define a formset
QuestionFormSet = formset_factory(QuestionForm)
# add initial data
formset = QuestionFormSet(initial=questions)
# should work because the field names are the same as that of form

if request.method == 'POST':
formset = QuestionFormSet(request.POST)
if formset.is_valid():
# associate answers here, note that you have access to the question id,
# which is a hidden field in your form





share|improve this answer
























  • This is great for adding questions, I'll probably be using this for that. It doesn't quite do what I want. What I'm trying for is auto generate a quiz attempt. The goal here is to make a bunch of new Question attempts associated with a Quiz attempt for the current

    – TicViking
    Mar 24 '11 at 19:35













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5423590%2fdjango-how-to-build-a-formset-for-a-quiz%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














If I am understanding your question correctly, you'll probably want to create a custom Form at execute time, and many custom Fields. I would expect something along the lines of:



class QuizForm(forms.Form):
def __init__(self, data, questions, *args, **kwargs):
self.questions = questions
for question in questions:
field_name = "question_%d" % question.pk
choices =
for answer in question.answer_set().all():
choices.append((answer.pk, answer.answer,))
## May need to pass some initial data, etc:
field = forms.ChoiceField(label=question.question, required=True,
choices=choices, widget=forms.RadioSelect)
return super(QuizForm, self).__init__(data, *args, **kwargs)
def save(self):
## Loop back through the question/answer fields and manually
## update the Attempt instance before returning it.


It will likely take additional tweaking to make this work through the admin interface, but this should give you a good start for constructing the form itself at execution time.



Your view would probably look something like:



# Assuming something like:  /quiz/69/ with "69" being the quiz PK.
def render_quiz(request, quiz_id):
quiz = get_object_or_404(Quiz, quiz_id)
form = QuizForm(questions=quiz.question_set.all())
if request.method == "POST":
form = QuizForm(request.POST, questions=quiz.question_set.all())
if form.is_valid(): ## Will only ensure the option exists, not correctness.
attempt = form.save()
return redirect(attempt)
return render_to_response('quiz.html', {"form": form})





share|improve this answer


























  • How can I be sure I'd get the same form back when I receive the post data?

    – TicViking
    Mar 24 '11 at 20:20













  • Forgot to include the view code. Updated. There is a race condition that exists if the Questions are updated between the time the Form is rendered and the time the answers are submitted. This should, however, show up as a question that was not answered (or that the answer doesn't exist, etc), and take the user back to the new form.

    – Jack M.
    Mar 24 '11 at 20:31











  • Thanks for the added explanation!

    – TicViking
    Mar 24 '11 at 21:46
















4














If I am understanding your question correctly, you'll probably want to create a custom Form at execute time, and many custom Fields. I would expect something along the lines of:



class QuizForm(forms.Form):
def __init__(self, data, questions, *args, **kwargs):
self.questions = questions
for question in questions:
field_name = "question_%d" % question.pk
choices =
for answer in question.answer_set().all():
choices.append((answer.pk, answer.answer,))
## May need to pass some initial data, etc:
field = forms.ChoiceField(label=question.question, required=True,
choices=choices, widget=forms.RadioSelect)
return super(QuizForm, self).__init__(data, *args, **kwargs)
def save(self):
## Loop back through the question/answer fields and manually
## update the Attempt instance before returning it.


It will likely take additional tweaking to make this work through the admin interface, but this should give you a good start for constructing the form itself at execution time.



Your view would probably look something like:



# Assuming something like:  /quiz/69/ with "69" being the quiz PK.
def render_quiz(request, quiz_id):
quiz = get_object_or_404(Quiz, quiz_id)
form = QuizForm(questions=quiz.question_set.all())
if request.method == "POST":
form = QuizForm(request.POST, questions=quiz.question_set.all())
if form.is_valid(): ## Will only ensure the option exists, not correctness.
attempt = form.save()
return redirect(attempt)
return render_to_response('quiz.html', {"form": form})





share|improve this answer


























  • How can I be sure I'd get the same form back when I receive the post data?

    – TicViking
    Mar 24 '11 at 20:20













  • Forgot to include the view code. Updated. There is a race condition that exists if the Questions are updated between the time the Form is rendered and the time the answers are submitted. This should, however, show up as a question that was not answered (or that the answer doesn't exist, etc), and take the user back to the new form.

    – Jack M.
    Mar 24 '11 at 20:31











  • Thanks for the added explanation!

    – TicViking
    Mar 24 '11 at 21:46














4












4








4







If I am understanding your question correctly, you'll probably want to create a custom Form at execute time, and many custom Fields. I would expect something along the lines of:



class QuizForm(forms.Form):
def __init__(self, data, questions, *args, **kwargs):
self.questions = questions
for question in questions:
field_name = "question_%d" % question.pk
choices =
for answer in question.answer_set().all():
choices.append((answer.pk, answer.answer,))
## May need to pass some initial data, etc:
field = forms.ChoiceField(label=question.question, required=True,
choices=choices, widget=forms.RadioSelect)
return super(QuizForm, self).__init__(data, *args, **kwargs)
def save(self):
## Loop back through the question/answer fields and manually
## update the Attempt instance before returning it.


It will likely take additional tweaking to make this work through the admin interface, but this should give you a good start for constructing the form itself at execution time.



Your view would probably look something like:



# Assuming something like:  /quiz/69/ with "69" being the quiz PK.
def render_quiz(request, quiz_id):
quiz = get_object_or_404(Quiz, quiz_id)
form = QuizForm(questions=quiz.question_set.all())
if request.method == "POST":
form = QuizForm(request.POST, questions=quiz.question_set.all())
if form.is_valid(): ## Will only ensure the option exists, not correctness.
attempt = form.save()
return redirect(attempt)
return render_to_response('quiz.html', {"form": form})





share|improve this answer















If I am understanding your question correctly, you'll probably want to create a custom Form at execute time, and many custom Fields. I would expect something along the lines of:



class QuizForm(forms.Form):
def __init__(self, data, questions, *args, **kwargs):
self.questions = questions
for question in questions:
field_name = "question_%d" % question.pk
choices =
for answer in question.answer_set().all():
choices.append((answer.pk, answer.answer,))
## May need to pass some initial data, etc:
field = forms.ChoiceField(label=question.question, required=True,
choices=choices, widget=forms.RadioSelect)
return super(QuizForm, self).__init__(data, *args, **kwargs)
def save(self):
## Loop back through the question/answer fields and manually
## update the Attempt instance before returning it.


It will likely take additional tweaking to make this work through the admin interface, but this should give you a good start for constructing the form itself at execution time.



Your view would probably look something like:



# Assuming something like:  /quiz/69/ with "69" being the quiz PK.
def render_quiz(request, quiz_id):
quiz = get_object_or_404(Quiz, quiz_id)
form = QuizForm(questions=quiz.question_set.all())
if request.method == "POST":
form = QuizForm(request.POST, questions=quiz.question_set.all())
if form.is_valid(): ## Will only ensure the option exists, not correctness.
attempt = form.save()
return redirect(attempt)
return render_to_response('quiz.html', {"form": form})






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 24 '11 at 20:28

























answered Mar 24 '11 at 20:18









Jack M.Jack M.

16.4k54462




16.4k54462













  • How can I be sure I'd get the same form back when I receive the post data?

    – TicViking
    Mar 24 '11 at 20:20













  • Forgot to include the view code. Updated. There is a race condition that exists if the Questions are updated between the time the Form is rendered and the time the answers are submitted. This should, however, show up as a question that was not answered (or that the answer doesn't exist, etc), and take the user back to the new form.

    – Jack M.
    Mar 24 '11 at 20:31











  • Thanks for the added explanation!

    – TicViking
    Mar 24 '11 at 21:46



















  • How can I be sure I'd get the same form back when I receive the post data?

    – TicViking
    Mar 24 '11 at 20:20













  • Forgot to include the view code. Updated. There is a race condition that exists if the Questions are updated between the time the Form is rendered and the time the answers are submitted. This should, however, show up as a question that was not answered (or that the answer doesn't exist, etc), and take the user back to the new form.

    – Jack M.
    Mar 24 '11 at 20:31











  • Thanks for the added explanation!

    – TicViking
    Mar 24 '11 at 21:46

















How can I be sure I'd get the same form back when I receive the post data?

– TicViking
Mar 24 '11 at 20:20







How can I be sure I'd get the same form back when I receive the post data?

– TicViking
Mar 24 '11 at 20:20















Forgot to include the view code. Updated. There is a race condition that exists if the Questions are updated between the time the Form is rendered and the time the answers are submitted. This should, however, show up as a question that was not answered (or that the answer doesn't exist, etc), and take the user back to the new form.

– Jack M.
Mar 24 '11 at 20:31





Forgot to include the view code. Updated. There is a race condition that exists if the Questions are updated between the time the Form is rendered and the time the answers are submitted. This should, however, show up as a question that was not answered (or that the answer doesn't exist, etc), and take the user back to the new form.

– Jack M.
Mar 24 '11 at 20:31













Thanks for the added explanation!

– TicViking
Mar 24 '11 at 21:46





Thanks for the added explanation!

– TicViking
Mar 24 '11 at 21:46













1














This is a rough idea of how it should work.



# define a form
class QuestionForm(forms.Form):
id = forms.IntegerField(widget=forms.HiddenInput) # make it hidden- i know, not very elegant
question = forms.CharField()
answer = forms.CharField()

# views.py
def display(request):
quiz = Quiz.objects.get(creator=request.user) # or some definition of quiz
questions = quiz.question_set.all().values('id','question') # to get question text

# define a formset
QuestionFormSet = formset_factory(QuestionForm)
# add initial data
formset = QuestionFormSet(initial=questions)
# should work because the field names are the same as that of form

if request.method == 'POST':
formset = QuestionFormSet(request.POST)
if formset.is_valid():
# associate answers here, note that you have access to the question id,
# which is a hidden field in your form





share|improve this answer
























  • This is great for adding questions, I'll probably be using this for that. It doesn't quite do what I want. What I'm trying for is auto generate a quiz attempt. The goal here is to make a bunch of new Question attempts associated with a Quiz attempt for the current

    – TicViking
    Mar 24 '11 at 19:35


















1














This is a rough idea of how it should work.



# define a form
class QuestionForm(forms.Form):
id = forms.IntegerField(widget=forms.HiddenInput) # make it hidden- i know, not very elegant
question = forms.CharField()
answer = forms.CharField()

# views.py
def display(request):
quiz = Quiz.objects.get(creator=request.user) # or some definition of quiz
questions = quiz.question_set.all().values('id','question') # to get question text

# define a formset
QuestionFormSet = formset_factory(QuestionForm)
# add initial data
formset = QuestionFormSet(initial=questions)
# should work because the field names are the same as that of form

if request.method == 'POST':
formset = QuestionFormSet(request.POST)
if formset.is_valid():
# associate answers here, note that you have access to the question id,
# which is a hidden field in your form





share|improve this answer
























  • This is great for adding questions, I'll probably be using this for that. It doesn't quite do what I want. What I'm trying for is auto generate a quiz attempt. The goal here is to make a bunch of new Question attempts associated with a Quiz attempt for the current

    – TicViking
    Mar 24 '11 at 19:35
















1












1








1







This is a rough idea of how it should work.



# define a form
class QuestionForm(forms.Form):
id = forms.IntegerField(widget=forms.HiddenInput) # make it hidden- i know, not very elegant
question = forms.CharField()
answer = forms.CharField()

# views.py
def display(request):
quiz = Quiz.objects.get(creator=request.user) # or some definition of quiz
questions = quiz.question_set.all().values('id','question') # to get question text

# define a formset
QuestionFormSet = formset_factory(QuestionForm)
# add initial data
formset = QuestionFormSet(initial=questions)
# should work because the field names are the same as that of form

if request.method == 'POST':
formset = QuestionFormSet(request.POST)
if formset.is_valid():
# associate answers here, note that you have access to the question id,
# which is a hidden field in your form





share|improve this answer













This is a rough idea of how it should work.



# define a form
class QuestionForm(forms.Form):
id = forms.IntegerField(widget=forms.HiddenInput) # make it hidden- i know, not very elegant
question = forms.CharField()
answer = forms.CharField()

# views.py
def display(request):
quiz = Quiz.objects.get(creator=request.user) # or some definition of quiz
questions = quiz.question_set.all().values('id','question') # to get question text

# define a formset
QuestionFormSet = formset_factory(QuestionForm)
# add initial data
formset = QuestionFormSet(initial=questions)
# should work because the field names are the same as that of form

if request.method == 'POST':
formset = QuestionFormSet(request.POST)
if formset.is_valid():
# associate answers here, note that you have access to the question id,
# which is a hidden field in your form






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 24 '11 at 19:26









gladysbixlygladysbixly

2,1181313




2,1181313













  • This is great for adding questions, I'll probably be using this for that. It doesn't quite do what I want. What I'm trying for is auto generate a quiz attempt. The goal here is to make a bunch of new Question attempts associated with a Quiz attempt for the current

    – TicViking
    Mar 24 '11 at 19:35





















  • This is great for adding questions, I'll probably be using this for that. It doesn't quite do what I want. What I'm trying for is auto generate a quiz attempt. The goal here is to make a bunch of new Question attempts associated with a Quiz attempt for the current

    – TicViking
    Mar 24 '11 at 19:35



















This is great for adding questions, I'll probably be using this for that. It doesn't quite do what I want. What I'm trying for is auto generate a quiz attempt. The goal here is to make a bunch of new Question attempts associated with a Quiz attempt for the current

– TicViking
Mar 24 '11 at 19:35







This is great for adding questions, I'll probably be using this for that. It doesn't quite do what I want. What I'm trying for is auto generate a quiz attempt. The goal here is to make a bunch of new Question attempts associated with a Quiz attempt for the current

– TicViking
Mar 24 '11 at 19:35




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5423590%2fdjango-how-to-build-a-formset-for-a-quiz%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas