Reputation: 66
I am new to programming, i have been learning django for the first time. I created a form using home.html file an i requested using POST method, but in the error it is giving the request method as GET. When I remove the method="POST" and put request.GET in views file, it is working fine. What am I doing wrong here?
home.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>
views.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'
Upvotes: 2
Views: 477
Reputation: 1086
Views.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})
urls.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 : if you want to the view called "add" in the app blog to handle the POST request, then ...
< 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>
Upvotes: 1