簡體   English   中英

Django-從POST請求中獲取價值

[英]Django - Taking value from 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)

我解決了問題。 正如themanatuf所說,我在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM