Django - 从POST请求获取值

时间:2017-05-10 12:45:31

标签: python django post request

我有一个区域列表,由id(整数)标识。 如何获取生成帖子请求的区域?

manual.html

{% if zone_list %}
    <ul>
        {% for z in zone_list %}
            <b><p>{{z.name}}</p></b>
            <form action="" method="post">
                {% csrf_token %}
                <input type="submit" name="{{z.id}}" value="ON"/>
                <input type="submit" name="{{z.id}}" value="OFF"/><br>
                <br>
                <label>Tiempo</label>:
                <input type="integerfield" name="Tiempo">
                <input type="submit" name="{{z.id}}" value="Start">
            </form>
        {% endfor %}
    </ul>
{% endif %}

在views.py中,我必须为动态表示区域

的内容更改1

views.py

def manual(request):
    if request.POST.has_key('1'):
        z = Zone.objects.get(id = 1)
        keyword = request.POST.get("1","")
        if keyword == "ON":
            #do something
        if keyword == "OFF":
            #do something
        if keyword == "Start":
            #do something
    zone_list = Zone.objects.all()
    context = {'zone_list':zone_list}
    return render(request, 'irrigation_controller/manual.html', context)

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。正如manatuf所说,我使用了带有zone_id的隐藏输入字段。

<强> manual.html

{% if zone_list %}
    {% for z in zone_list %}
        <b><p>{{z.name}}</p></b>
        <form action="" method="post">
            {% csrf_token %}
            <input type="hidden" name="zone_id" value="{{z.id}}">
            <input type="submit" name="order" value="ON"/>
            <input type="submit" name="order" value="OFF"/><br>
            <br>
            <label>Tiempo</label>:
            <input type="integerfield" name="Tiempo">
            <input type="submit" name="order" value="Start">
        </form>
    {% endfor %}
{% endif %}

在视图中,我阅读了zone_id和订单。

<强> views.py

def manual(request):
if request.POST.has_key('zone_id'):
    z = Zone.objects.get(id = request.POST.get("zone_id",""))
    keyword = request.POST.get("order","")
    if keyword == "ON":
        z.irrigation_on()
    if keyword == "OFF":
        z.irrigation_off()
    if keyword == "Start":
        tiempo = request.POST['Tiempo']
        tiempo = float(tiempo)
        irrigation_time.delay(z.id, tiempo)
zone_list = Zone.objects.all()
context = {'zone_list':zone_list}
return render(request, 'irrigation_controller/manual.html', context)