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
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
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"]
Related
I have html template, and python function(driver_links), my functional work but I have the wrong link
html template (driver_id.html):
{{key[0]}}
function:
#app.route("/report/drivers/<driver_id>")
def driver_links(driver_id):
context = {
"report": sort_asc_desc('data', 'asc'),
"test": driver_id
}
return render_template('driver_id.html', **context)
wrong link I have: http://127.0.0.1:5000/report/drivers/SVF
if I change #app.route in function(driver_links) to:
#app.route("/report/drivers/")
I get a correct link, but function doesn't work
example correct link: http://127.0.0.1:5000/report/drivers/?driver_id=SVF
Choose between variable rules or url parameters.
If you use the former, the required, extracted parameter is passed as a variable to the function.
#app.route("/report/drivers/<driver_id>")
def driver_links(driver_id):
# ...
With the latter, you have to ask for the optional parameter from the dictionary request.args and no arguments are passed to the function.
from flask import request
#app.route("/report/drivers/")
def driver_links():
driver_id = request.args.get('driver_id')
# ...
Note that you can specify a default value and a type conversion here. You can find the documentation for this here.
I have recently started to learn and work on Django i came across this error multiple times sometimes it was due to repetitive use of a name in an html and sometimes it was due the part for example "variable_name=request.POST['variable_name']"
I visited various sites regarding this error and was able to find a solution i.e, once i have typed in "variable_name=request.POST['variable_name']" in a function in views.py
the next time i tried to POST the data again "variable_name=request.POST['variable_name']" I had to do something like this "variable_name=request.POST.get('variable-name', 'blank_or_whatever_canBeFalseAlso')
The Above statement helped me solve that error I got this solution from A Thread in StackOverflow itself Quite a useful site.
Now for the Question am just Curious to know whats the difference between
Variable_Name=request.POST['Variable_Name']
Variable_Name=request.POST.get('Variable_Name','Whatever')
Code (views.py) Is given Below:
from django.shortcuts import render
from . import views
from datetime import date
from .models import Batch, Deleted_Batch
from django.utils.datastructures import MultiValueDictKeyError
# Create your views here.
today = date.today()
Date_Batch = str(today.day)+'/'+str(today.month)+'/'+str(today.year)
def Reg_Batch(request):
return render(request, 'Reg_Batch.html',{'Date_Batch':Date_Batch})
def Reg_Batch_Receive(request):
Region_Code=request.POST['Region_Code']
Branch_Code=request.POST['Branch_Code']
Batch_Number=request.POST['Batch_Number']
Farm_Code=request.POST['Farm_Code']
Farm_Status=request.POST['Farm_Status']
Farmer_Name=request.POST['Farmer_Name']
Farmer_Address=request.POST['Farmer_Address']
Farmer_Phone_Number=request.POST['Farmer_Phone_Number']
Farmer_Email=request.POST['Farmer_Email']
return render(request, 'Reg_Batch_Receive.html')
def Reg_Batch_View(request):
Region_Code=request.POST.get('Region_Code', 'Blank')
Branch_Code=request.POST.get('Branch_Code', 'Blank')
Farm_Code=request.POST.get('Farm_Code', 'Blank')
Farm_Status=request.POST.get('Farm_Status', 'Blank')
return render(request, 'Reg_Batch_View.html',{'Region_Code':Region_Code,'Branch_Code':Branch_Code,'Farm_Code':Farm_Code,'Farm_Status':Farm_Status})
def Reg_Batch_View_Receive(request):
Date_Batch= '20/08/2000'
Region_Code='586001'
Branch_Code='586001'
Batch_Number='586001'
Farm_Code='5484712'
Farm_Status='Active'
Farmer_Name='Joel Liao'
Farmer_Address='jojojojojojojo'
Farmer_Phone_Number='8088078086'
Farmer_Email='kuroneko#gmail.com'
return render(request,'Reg_Batch_View_Receive.html',{'Date_Batch':Date_Batch,'Region_Code':Region_Code,'Branch_Code':Branch_Code,'Batch_Number':Batch_Number,'Farm_Code':Farm_Code,'Farm_Status':Farm_Status,'Farmer_Name':Farmer_Name,'Farmer_Address':Farmer_Address,'Farmer_Phone_Number':Farmer_Phone_Number,'Farmer_Email':Farmer_Email})
def Reg_Batch_Delete(request):
Region_Code='586001'
Branch_Code='586001'
Batch_Number='586001'
Farm_Code='5484712'
Farm_Status='Active'
Farmer_Name='Joel Liao'
Farmer_Address='jojojojojojojo'
Farmer_Phone_Number='8088078086'
Farmer_Email='kuroneko#gmail.com'
Deleted_Batch_DataBase=Deleted_Batch({'Region_Code':Region_Code,'Branch_Code':Branch_Code,'Batch_Number':Batch_Number,'Farm_Code':Farm_Code,'Farm_Status':Farm_Status,'Farmer_Name':Farmer_Name,'Farmer_Address':Farmer_Address,'Farmer_Phone_Number':Farmer_Phone_Number,'Farmer_Email':Farmer_Email}),
return render(request,'Reg_Batch_Delete.html',{'Batch_Number':Batch_Number})
def Reg_Batch_Delete_Receive(request):
Batch_Number='586001'
return render(request,'Reg_Batch_Delete_Receive.html',{'Batch_Number':Batch_Number})
request.POST is a dictionary-like object (see docs).
So if you do
request.POST['foobar']
you can access the posted variable foobar. But if this is not being posted and therefore not set inside POST, you will get the MultiValueDictKeyError.
This is similar to access a key inside a default dictionary which is not set, e.g.
d = {}
d['foobar'] # raises Exception
In order to avoid this error, you can then do
request.POST.get('foobar', 'default-value')
in order to get the posted field and a default if it is not present.
So if foobar isn't set inside your POST-data, the received value is default-value.
This is similar to the default dictionary handling:
d = {}
d.get('foobar', 'random') # returns 'random'
I'm trying to pass a number through URL and retrieve it on another page. If I try to specify the variable type, i get a malformed URL error and it won't compile. If I don't specify the var type, it will run, but the variable becomes Type None. I can't cast it to an int either. How can I pass it as an Integer...? Thanks in advance.
This gives me a malformed URL error:
#app.route('/iLike/<int: num>', methods=['GET','POST'])
def single2(num):
This runs but gives me a var of type none that I can't work with:
#app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
**num = request.args.get('num')**
You are mixing route parameters and request arguments here.
Parameters you specify in the route are route parameters and are a way to declare variable rules. The values for these parameters are passed as function arguments to the route function. So in your case, for your <num> url part, the value is passed as the function argument num.
Request arguments are independent of routes and are passed to URLs as GET parameters. You can access them through the request object. This is what you are doing with request.args.get().
A full example would look like this:
#app.route('/iLike/<int:num>')
def single2(num):
print(num, request.args.get('num'))
Opening /iLike/123 would now result in 123 None. The request argument is empty because you didn’t specify one. You can do that by opening /iLike/123?num=456, which would result in 123 456.
You recieve None here:
num = request.args.get('num')
because you're not passing num as element of querystring.
When use request.args.get('num')?
If we would have URL like this one:
localhost:8080/iLike?num=2
But it's not your case. You pass num already to a function as an argument. So in your case just use:
#app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
print(num)
In your second example, instead of num = request.args.get('num') try to simply use num. Since you specified it as an input to your route/function, you should be able to access it directly.
Try this:
#app.route('/iLike/<int:num>', methods=['GET','POST'])
def single2(num):
print(num)
Other issues aside, the direct cause of the "malformed URL" error is the space you included in the URL:
'/iLike/<int: num>'
Instead of this:
'/iLike/<int:num>'
So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests. The address being used is:
http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296
I'm trying to write a simple web view that can access this url and return a JSON packet as the result (worried about actual element values/layout later).
Here's my simple attempt at just alerting/returning the data:
$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?",
function(json){
alert(json);
<!--$.each(json.items, function(i,item){
});-->
});
I am able to access this URL directly, either at http://localhost:8000/api/0.1/tonight-mobile.json or http://localhost:8000/api/0.1/tonight-mobile.json&callback=jsonp1290277462296 and get back a valid JSON packet... So I'm assuming it's in my noob javascript:)
My views.py function that is generating this response looks as follows:
def tonight_mobile(request):
callback = request.GET.get('callback=?', '')
def with_rank(rank, place):
return (rank > 0)
place_data = dict(
Places = [make_mobile_place_dict(request, p) for p in Place.objects.all()]
)
xml_bytes = json.dumps(place_data)
xml_bytes = callback + '(' + xml_bytes + ');'
return HttpResponse(xml_bytes, mimetype="application/json")
With corresponding urls.py configuration:
(r'^tonight-mobile.json','iphone_api.views.tonight_mobile'),
I am still somewhat confused on how to use callbacks, so maybe that is where my issue lies. Note I am able to call directly a 'blah.json' file that is giving me a response, but not through a wired URL. Could someone assist me with some direction?
First, callback = request.GET.get('callback=?', '') won't get you the value of callback.
callback = request.GET.get( 'callback', None )
Works much better.
To debug this kind of thing. You might want to include print statements in your Django view function so you can see what's going on. For example: print repr(request.GET) is a helpful thing to put in a view function so that you can see the GET dictionary.
if i have this URL in from python code on appengine
http://localhost:8080/blog/view/2f1cab5844fb432b8426ae666c4ac493
how can i get the value of the key : 2f1cab5844fb432b8426ae666c4ac493
#Herms answer will work, but you may prefer this instead:
In the code that creates your webapp instance, capture the key part of the URL with a regex, like:
def main():
application = webapp.WSGIApplication( [
(r'/blog/view/(\w+)', MyBlogViewHandler),
## others listed here...
])
...then code your handler class like this - the key you captured will be passed to your get() method as an argument:
class MyBlogViewHandler(webapp.RequestHandler):
def get(self, key):
# do something useful with the 'key' argument
You can access the requested URL via self.request, assuming you're extending the standard webapp.RequestHandler class. That will give you access to the path and query, and you should be able to extract the values you want from the path.
Here's some documentation on the Request object:
http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html