Reputation:
I'm watching a lecture about Django. The lecturer explains everything wonderfully but didn't go into much detail into "an API I effectively created". This is my first time meddling with this so I'm a bit unsure.
What I don't understand is specifically this line request.GET.get("start")
. How does one make that work in the index.html file (with embedded js script) by just using a fetch?
views.py
def posts(request):
# Get start and end points
start = int(request.GET.get("start") or 0)
end = int(request.GET.get("end") or (start + 9))
# Generate list of posts
data = []
for i in range(start, end + 1):
data.append(f"Post #{i}")
# Artificially delay speed of response
time.sleep(1)
# Return list of posts
return JsonResponse({
"posts": data
})
index.html
fetch(`/posts?start=${start}&end=${end}`)
.then(response => response.json())
.then(data => {
data.posts.forEach(add_post);
})
Upvotes: 1
Views: 240
Reputation: 31
The request object contains information about the user's request. What data they've sent to the page, where they are coming from, etc.
request.GET contains the GET variables. These are what you see in your browser's address bar. The .get() method is a method used for dictionaries. What your snippet of code is doing is saying, "Get the value of a GET variable with name 'page', and if it doesn't exist, return 1".
Likewise, you will see request.POST used when a user submits a form.
For the specific example posted: start = int(request.GET.get("start") or 0) end = int(request.GET.get("end") or (start + 9))
fetch(/posts?start=${start}&end=${end}
)
eg. http://127.0.0.1:8000/posts?start=10&end=20 This will fetch post#10 to post#20 from the API.
You can change these start & end variable to first and last or anything else it would work same.
Upvotes: 2