Lately I have been trying to use the GET request in django-python. However I run into a 404 error when I do so. I want the program to print the parameter given to it.
URL PATTERN :
path('add<int:hello>/',views.add,name = 'Add')
VIEWS.PY:
def add(request,num1):
val1 = request.GET["num1"]
return HttpResponse(request,"Hello")
WHAT I AM SEARCHING ON BROWSER:
http://127.0.0.1:8000/add?1
CodePudding user response:
A couple of things are strange or broken here.
Given path('add<int:hello>/', views.add, ...)
,
Django expects that function views.add
has the following signature:
def add(request, hello):
The pattern 'add<int:hello>/'
expects urls with "add" followed by an integer, such as:
http://127.0.0.1:8000/add1 http://127.0.0.1:8000/add2 http://127.0.0.1:8000/add3 ...
and so on.
request.GET["num1"]
expects urls that have num1=...
in their query string, such as:
http://127.0.0.1:8000/add1?num1=...
HttpResponse
expects a string type as its first parameter,
not an HttpRequest
type as in the posted code.
Fixing the problems
This might be close to what you want, and it will work:
path('add<int:num1>/', views.add, name='Add')
def add(request, num1):
return HttpResponse(f"Hello {num1}")
# visit http://127.0.0.1:8000/add1
Another variation:
path('add', views.add, name='Add')
def add(request):
num1 = request.GET['num1']
return HttpResponse(f"Hello {num1}")
# visit http://127.0.0.1:8000/add?num1=123
CodePudding user response:
http://127.0.0.1:8000/add?hello=1
This should work. you need to add the query param name as well.
To get the value you need to use this code:
request.GET["hello"]