[英]Django 1.9 read value from request.POST
因此,我正在嘗試編寫一個腳本,該腳本將詢問用戶一些問題,並根據他們選擇的答案執行操作。 我是Django的新手,所以我仍然不確定它是如何工作的,因此我將代碼基於其網站上的教程(直到獲得更好的理解) https://docs.djangoproject。 com / zh / 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.