簡體   English   中英

無法在 html 表單中使用 post 方法返回。 我究竟做錯了什么?

[英]Unable to return using post method in an html form. what am i doing wrong?

我是編程新手,我第一次學習 django。 我使用 home.html 文件創建了一個表單,我使用 POST 方法請求,但在錯誤中它將請求方法指定為 GET。 當我刪除 method="POST" 並將 request.GET 放入視圖文件時,它工作正常。 我在這里做錯了什么?

主頁.html

< form action="add" method="POST">

    {% csrf_token %}

    Enter 1st number : <input type="text" name="num1"><br>
    Enter 2nd number : <input type="text" name="num2"><br>
    <input type="submit">

</form>

視圖.py

def add(request):

    val1= int(request.POST['num1'])
    val2= int(request.POST['num2'])
    res= val1 +val2

    return render(request, 'result.html' ,{'result': res})

I am getting the following error: MultiValueDictKeyError at /add 'num1' Request Method: GET Request URL: http://127.0.0.1:8000/add?num1=17&num2=4 Django Version: 4.0.1 Exception Type: MultiValueDictKeyError Exception Value :
'num1'

視圖.py

def add(request):
    if request.method == "POST":
        #LOGIC AS TO WHAT TO SERVE WHEN THIS VIEW RECIEVES A POST REQUEST
        val1= int(request.POST.get('num1'))
        val2= int(request.POST.get('num2'))
        res= val1 +val2
        return render(request, 'result.html' ,{'result': res})

    else:
        #serves non POST request , ie GET in this case
        ...your GET REQUEST LOGIC
        return render(request, 'GETREQUESTPAGE.html' ,{'param1': paramval})

網址.py:

# blog.urls
from django.urls import path

from . import views
#example consider a url for app named blog... mention the app name in the urls.py as below
app_name = 'blog'
urlpatterns = [
    path('', views.index(), name='add'),
]

home.html:如果你想在應用博客中名為“ add ”的視圖來處理POST請求,那么...

< form action="{% url blogs.add %}" method="POST">

    {% csrf_token %}

    Enter 1st number : <input type="text" name="num1"><br>
    Enter 2nd number : <input type="text" name="num2"><br>
    <input type="submit">

</form>

暫無
暫無

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

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