Django 1.9 从 request.POST 读取值

Django 1.9 read value from request.POST

所以我正在尝试制作一个脚本,该脚本会询问用户一些问题,并根据他们选择的答案执行操作。 我是 Django 的新手,所以我仍然不确定它是如何完全工作的,所以我的代码基于他们网站上的教程(直到我更好地理解) 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>

我卡在 views.py 代码上了。我想读取 selected_option 值,这样我就可以根据所选内容 运行 执行所需的操作。

if selected_option == 'value':
    perform action
elif selected_option == 'value2':
    perform other action

到目前为止,selected_option 是一个对象,所以使用 if selected_option == 'value' 不是很有用。另一方面,您可以将 selected_option 的属性与数字和字符串等任意事物进行比较,例如:

if selected_option.id == 1: return True  # Will return True if the option chosen has an ID of 1

if selected_option.option_text == 'SOME OPTION TEXT': return True  # Will return True if the option chosen matches the option text I compared it to