Forewarning: I'm very new to Django (and web development, in general).
I'm using Django to host a web-based UI that will take user input from a short survey, feed it through some analyses that I've developed in Python, and then present the visual output of these analyses in the UI.
My survey consists of 10 questions asking a user how much they agree with a a specific topic.
Example of UI for survey:
For models.py, I have 2 fields: Question & Choice
class Question(models.Model):
question_text = models.CharField(max_length=200)
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=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
I am wanting to have a user select their response to all 10 questions, and then click submit to submit all responses at once, but I'm having trouble with how that would be handled in Django.
Here is the html form that I'm using, but this code snippet places a "submit" button after each question, and only allows for a single submission at a time.
NOTE: The code below is creating a question-specific form for each iteration.
{% for question in latest_question_list %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-topic">
<label>{{ question.question_text }}</label>
</div>
{% for choice in question.choice_set.all %}
<div class="col-select">
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
</div>
{% endfor %}
</div>
<input type="submit" value="Vote" />
</form>
{% endfor %}
I'm interested in how I would take multiple inputs (all for Question/Choice) in a single submission and return that back to views.py
EDIT: ADDING VIEWS.PY
Currently, my views.py script handles a single question/choice pair. Once I figure out how to allow users to submit the form one time for all 10 question/choices, I will need to reflect this in views.py. This could sort of be part 2 of the question. First, how do I enable a user to submit all of their responses to all 10 questions with one "submit" button? Second, how do I setup views.py to accept more than 1 value at a time?
views.py
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/survey.html', {
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:analysis'))
Please let me know if additional context it needed.
Thanks in advance!
-C