Trying to implement poll-creating system, where I can create questions with choices (previously I did this all in the admin, and had to create an individual choice object for every choice)
Here's my models:
class Question(models.Model):
has_answered = models.ManyToManyField(User, through="Vote")
question_text = models.CharField(max_length=80)
date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=100)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
So right now here's the template:
<form method="post" action="">{% csrf_token %}
{{ question_form.question_text }}
<br><br>
<!--{{ choice_form.choice_text|placeholder:"Choice" }}-->
<input class="choice" name="choice_text" placeholder="Choice" type="text" />
<input class="choice" name="choice_text" placeholder="Choice" type="text" />
<input class="choice" name="choice_text" placeholder="Choice" type="text" />
<img src="{% static 'images/plus.png' %}" class="add_choice" />
<br>
<button class="submit" type="submit">Create question</button>
</form>
As you can see I'm not sure whether using multiple {{ choice_form.choice_text|placeholder:"Choice" }} is possible. So I paste multiple input fields and tried to get all of them by using getList(). However I get this error:
'QueryDict' object has no attribute 'getList'
Any idea why? Here's my views:
def questions(request):
question_form = QuestionForm(request.POST or None)
choice_form = ChoiceForm(request.POST or None)
if request.POST:
choice = request.POST.getList('choice_text')
print(choice)
if request.user.is_authenticated():
if question_form.is_valid():
print('valid question')
#question = question_form.save(commit=False)
return render(request, 'questions.html', {'question_form': question_form, 'choice_form': choice_form})
So how exactly should I go about this, for grabbing every choice input? Eventually I want to make all these choices map to the question that was entered. But as I said I'm sure sure whether it's possible to have multiple instances of the same field in one form.
Try using getlist instead of getList.
Also consider using forms, specifically the MultipleChoiceField could be useful in your scenario.