Doug Smith
Doug Smith

Reputation: 580

How to add to ManyToMany when getting "no attribute" error?

Using a form, I'm trying to add items to the manytomany field questions of a Quiz object after first getting a queryset of the questions I want to add. I save the ModelForm but when I add the item, I get an AttributError: 'function' object has no attribute 'questions'

Previously I was able to create a Quiz object with 3 random questions using a save method in the model. However, I don't see a way to add 3 questions from a particular queryset using only the model

views.py

def choose(request, obj_id):
    """Get the id of the LearnObject of interest"""
    """Filter the questions and pick 3 random Qs"""
    my_qs = Question.objects.filter(learnobject_id=obj_id)
    my_qs = my_qs.order_by('?')[0:3]
    if request.method == 'POST':
        form = QuizForm(request.POST)
        if form.is_valid():
            new_quiz = form.save
            for item in my_qs:
                new_quiz.questions.add(item)
            new_quiz.save()
            return HttpResponseRedirect('/quizlet/quiz-list')
    else:
        form = QuizForm()  
    return render(request, 'quizlet/quiz_form.html', {'form': form})

and models.py

class LearnObject(models.Model):
    """model for the learning objective"""
    code = models.CharField(max_length=12)
    desc = models.TextField()

class Question(models.Model):
    """model for the questions."""
    name = models.CharField(max_length=12)
    learnobject = models.ForeignKey(
        LearnObject, on_delete=models.CASCADE,
        )
    q_text = models.TextField()
    answer = models.CharField(max_length=12)

class Quiz(models.Model):
    """quiz which will have three questions."""
    name = models.CharField(max_length=12)
    questions = models.ManyToManyField(Question)
    completed = models.DateTimeField(auto_now_add=True)
    my_answer = models.CharField(max_length=12)

class QuizForm(ModelForm):
    """test out form for many2many"""
    class Meta:
        model = Quiz
        fields = ['name', 'my_answer']

The error happens at the line new_quiz.questions.add(item). I don't understand this since the model of Quiz has a field questions, and the object (I think) has a already been created on the first new_quiz = form.save()

Upvotes: 0

Views: 176

Answers (1)

edgarzamora
edgarzamora

Reputation: 1504

The error is in the next line: new_quiz = form.save, you are missing the (), change it to new_quiz = form.save().

If not you are saving the reference of the function form.save to the new_quiz, instead of the object returned by the function.

Upvotes: 1

Related Questions