So I'm trying to make a script that would ask users a few questions and based on the answers they have chosen, perform an action. I'm very new to Django so I'm still not sure on how it fully works and so I'm basing my code off the tutorial found on their website (until I get a better understanding) https://docs.djangoproject.com/en/1.9/intro/tutorial01/
models.py
@python_2_unicode_compatible
class Question(models.Model):
question_text = models.CharField(max_length=300)
def __str__(self):
return self.question_text
@python_2_unicode_compatible
class Option(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
option_text = models.CharField(max_length=400)
def __str__(self):
return self.option_text
views.py
def select(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_option = question.option_set.get(pk=request.POST['option'])
except (KeyError, Option.DoesNotExist):
return render(request, 'awsservers/detail.html', {
'question':question,
'error_message': "You did not select an option.",
})
if selected_option:
# run code here
return HttpResponseRedirect(reverse('awsservers:extra', args=(question.id,)))
detail.html
<h2>{{ question.question_text }}</h2>
<form action="{% url 'awsservers:select' question.id %}" method="post">
{% csrf_token %}
{% for option in question.option_set.all %}
<input type = "radio" name = "option" id = "option{{ forloop.counter }}" value = "{{ option.id }}" />
<label for = "option{{ forloop.counter }}">{{ option.option_text }}</label><br />
{% endfor %}
<br>
<input type="submit" value="Select" />
</form>
<a href="{% url 'awsservers:index' %}">Go Back</a>
I'm stuck at views.py code. I would like to read the selected_option value so I can run the required action based on what is selected.
if selected_option == 'value':
perform action
elif selected_option == 'value2':
perform other action