I have a form to let users make a new poll, it consists of 2 ModelForms one for the Question model and another for the Choice model
a screenshot:
i want there to be something like a (+) or (add another choice) button where users can add as many choices as they want and then submit it all.
here's the models.py file
models.py
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
questionText = models.CharField(max_length=150)
datePublished = models.DateTimeField(auto_now_add=True)
def str(self):
return self.questionText
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choiceText = models.CharField(max_length=200)
choiceVotes = models.IntegerField(default=0)
def str(self):
return self.choiceText
forms.py
from django import forms
from .models import Question
from .models import Choice
class NewPollForm(forms.ModelForm):
class Meta:
model = Question
labels = {
"questionText":"Poll question"
}
fields = ("questionText",)
class NewChoicesForm(forms.ModelForm):
class Meta:
model = Choice
labels = {
"choiceText":"Choice"
}
fields = ("choiceText",)
the view for this form's page you can see it is set for only one choice field right now
from .forms import NewPollForm
from .forms import NewChoicesForm
def newpoll(request):
if request.user.is_authenticated == True :
pass
else:
return redirect("users:signup")
if request.method == "POST":
qform = NewPollForm(request.POST)
cform = NewChoicesForm(request.POST)
if qform.is_valid():
newpoll = qform.save(commit=False)
newpoll.user = request.user
newpoll.datePublished = timezone.now()
newpoll.save()
cform.instance.question = newpoll
cform.save()
return redirect("polls:details", pollid=newpoll.pk)
else:
return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})
else:
qform = NewPollForm()
cform = NewChoicesForm()
return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})