Django 1.9从request.POST读取值

时间:2016-01-07 03:31:08

标签: python django django-1.9

所以我试图制作一个脚本,询问用户几个问题,并根据他们选择的答案,执行一个动作。 我对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

1 个答案:

答案 0 :(得分:0)

截至目前,$(function() { $(document).on('click', '.tiles', function() { $(".activeTile").removeClass("activeTile"); $(this).addClass("activeTile"); }); }); 是一个对象,因此使用selected_option并不是很有用。另一方面,您可以将if selected_option == 'value'的属性与数字和字符串等任意内容进行比较,例如:

selected_option

OR

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