Uncle Toby
Uncle Toby

Reputation: 377

'Questions ' object is not iterable Django

I have a model called Question. Model allow users to create new questions. I'm trying to populate multiple forms with a queryset of objects. The problem appears when I attempt to initial with a queryset. I get this error

 'Question' object is not iterable


File "C:\mysite\pet\views.py" in DisplayAll
294.             formset = form(initial=q)

models.py

class Question(models.Model):
    question= models.CharField(max_length=500)
    user = models.ForeignKey(User)

forms

class QuestionForm(forms.ModelForm):
question= forms.CharField(required=True,max_length=51)
class Meta:
    model = Question
    fields = ('question',)

views

def DisplayAll(request):
    q = Question.objects.filter(user=request.user)

    form = formset_factory(QuestionForm)
    formset = form(initial=q)
    return render(request,'question.html',{'formset':formset})

template

 {% for f in formset %}
 {{f}}
 {% endfor %}

Upvotes: 19

Views: 51072

Answers (1)

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11048

Initial expects a dictionary of values, so you just need to change your queryset like this:

q = Question.objects.filter(user=request.user).values()

See the docs about values()

Upvotes: 28

Related Questions