Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms Newbie Question

Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a link to a good book that covers this topic, as an answer. Basically, this is how it breaks down, I have 3 models (quiz, questions, answers). I have 20 questions, with 4 potential answers (multi-choice), per quiz. The numbers can vary, but you get the point.

I need to create a form for these items, much like you'd expect in a multiple choice quiz. However, when I create the form by hand in the templates, rather than using django.forms, I get the following:

invalid literal for int() with base 10: 'test'

So I'm trying to mess with the django.forms, but I guess I'm just not grasping the idea of how to build a proper form out of those. Any help would be greatly appreciated, thanks.

For what it's worth here are the models:

class Quiz(models.Model):
    label = models.CharField(blank=True, max_length=400)
    slug = models.SlugField()

    def __unicode__(self):
        return self.label

class Question(models.Model):
    label = models.CharField(blank=True, max_length=400)
    quiz = models.ForeignKey(Quiz)

    def __unicode__(self):
        return self.label

class Answer(models.Model):
    label = models.CharField(blank=True, max_length=400)
    question = models.ForeignKey(Question)
    correct = models.BooleanField()

    def __unicode__(self):
        return self.label
like image 791
f4nt Avatar asked Mar 01 '23 22:03

f4nt


1 Answers

Yeah I have to agree the documentation and examples are really lacking here. The is no out of the box solution for the case you are describing because it goes three layers deep: quiz->question->answer.

Django has model inline formsets which solve the problem for two layers deep. What you will need to do to generate the form you want is:

  1. Load up a quiz form (just a label text box from your model)
  2. Load a an question formset: QuestionFormSet(queryset=Question.objects.filter(quiz=quiz))
  3. For each question load up a answer formset in much the same way you load up the question formset
  4. Make sure you save everything in the right order: quiz->question->answer, since each lower level needs the foreign key of the item above it
like image 165
Jason Christa Avatar answered Mar 11 '23 13:03

Jason Christa