Sunday, February 20, 2011

How to assign form names in formset before rendering??

Hi all...

I'm working on building an oline examination system. Here is a view
which picks some questions randomly from the database and generates 10
questions.

I could able to display these questions on the web page. In that web
page there should be a formset which have options A, B, C, D. The name
of the form in that "formset" should be the unique question ID which I
gave.

How to assign form ID to each form in a "frameset" Before it renders
to the user??

Please give me your suggestions. I don't have any Idea on this.

Here is the view which calculates the random questions.

//*********views.py***************//

from django.forms.formsets import formset_factory


def start_exam(request, sub_code, template_name = 'accounts/
start_exam.html', answer_form=AnswerForm, current_app=None,
extra_context=None):

nq_in_exam = 10

if request.method == "POST":
//some logic goes here to process the submitted form.
else:
questions = Question.objects.filter(subject_code = sub_code)

n = questions.count()
if (n < nq_in_exam):
return render_to_response(template_name)

m = int(math.floor(n/nq_in_exam))

position = 0
temp_list=[]
id_list = []

for object in Question.objects.filter(subject_code = sub_code):
temp_list.append(object.id)

for i in range(nq_in_exam):
id_list.append(temp_list[int(position
+math.floor(random.random()*m))])
position +=m

exam = Question.objects.filter(id__in = id_list)

formset = formset_factory(answer_form)

context = { 'formset': formset, 'questions':exam }

context.update(extra_context or {})

return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))


------------------------------------------------------------------------------------------------------------------------------------------------------------------
Here is the form which is to be in formset.

//*********forms.py*****************//

ANSWER_CHOICES = (('A','A'),('B','B'),('C','C'),('D','D'))

class AnswerForm(forms.Form):
options = forms.ChoiceField(choices = ANSWER_CHOICES, widget =
forms.RadioSelect())

---------------------------------------------------------------------------------------------------------------------------------------------------------------
Here is the template logic I have written to render that page.

<form name = "exam_form" action ="." method ="POST">
{%for form in formset%}
{{form}}
{%endfor%}
<input type="submit" value="submit" />
</form>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate