1

I'm trying to create a Quiz with a number of questions the user inputs in a form (also with a tag, but that's not the point here). I've tried the following but I do not feel this is the right approach. I am thinking there must be another way instead of manually calling Quiz.objects.create() with data I got from the form. Also even if the Quiz object gets created, I'm getting the following error:

'NoneType' object has no attribute '__dict__'

models.py

class Quiz(models.Model):
    name = models.CharField(max_length=100)
    number_of_questions = models.IntegerField(default=5)
    time_limit = models.IntegerField(default=300)
    questions = models.ManyToManyField(Question)

forms.py

class QuizForm(forms.ModelForm):
    class Meta:
        model = Quiz
        exclude = ['questions']

    def save(self):
        data = self.cleaned_data
        questions = get_questions_with_tag('example_tag')
        questions = questions[:data['number_of_questions']]
        quiz = Quiz.objects.create(name=data['name'],
                               time_limit=data['time_limit'],
                               number_of_questions=data['number_of_questions'])
        for q in questions:
            quiz.questions.add(q)

        quiz.save()

views.py

class AddQuizView(CreateView):
    template_name = 'quiz/cpanel/add_quiz.html'
    form_class = QuizForm
    success_url = reverse_lazy('list_quizzes')

Can you suggest a better approach that will involve only adding the questions list to the form request?

2
  • Where are the questions coming from? What is get_questions_with_tag? Oct 8, 2014 at 14:20
  • It's a list of objects of type Question. I'm just querying the database there: Question.objects.filter(tag__name=tag) Oct 8, 2014 at 15:37

1 Answer 1

0

After few more tries, I came up with this:

def save(self):
    data = self.cleaned_data

    questions = get_questions_with_tag('example_tag')
    questions = questions[:data['number_of_questions']]

    self.instance.save()
    self.instance.questions = questions

    quiz.save()

It fixes the error I had and also I'm no longer manually creating an object of type Quiz.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.