Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 48 additions & 36 deletions djangoWorldClock/worldClock/views.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,54 @@
from django.shortcuts import render, redirect
import requests

# Create your views here.
def home(request):
return render(request, "home.html")
return render(request, "home.html")

def search(request):

# If the request method is not POST, redirect to the home page
if request.method != "POST":
return redirect("/")

# Get the search query
query = request.POST.get("q", "")

try:
# Pass the search query to the Nominatim API to get a location
location = requests.get(
"https://nominatim.openstreetmap.org/search",
{"q": query, "format": "json", "limit": "1"},
).json()

# If a location is found, pass the coordinate to the Time API to get the current time
if location:
coordinate = [location[0]["lat"], location[0]["lon"]]

time = requests.get(
"https://timeapi.io/api/Time/current/coordinate",
{"latitude": coordinate[0], "longitude": coordinate[1]},
)

return render(
request, "success.html", {"location": location[0], "time": time.json()}
)

# If a location is NOT found, return the error page
else:

return render(request, "fail.html")
except Exception as error:
return render(request, "500.html")
# If the request method is not POST, redirect to the home page
if request.method != "POST":
return redirect("/")

# Get the search query
query = request.POST.get("q", "")

try:
# Add proper headers for Nominatim API
headers = {
'User-Agent': 'Django World Clock App (your-email@example.com)'
}

# Pass the search query to the Nominatim API to get a location
location_response = requests.get(
"https://nominatim.openstreetmap.org/search",
params={"q": query, "format": "json", "limit": "1"},
headers=headers
)

# Check if the response is successful before trying to parse JSON
if location_response.status_code == 200:
location = location_response.json()
else:
return render(request, "500.html")

# If a location is found, pass the coordinate to the Time API to get the current time
if location:
coordinate = [location[0]["lat"], location[0]["lon"]]

time_response = requests.get(
"https://timeapi.io/api/Time/current/coordinate",
params={"latitude": coordinate[0], "longitude": coordinate[1]},
)

if time_response.status_code == 200:
return render(
request, "success.html", {"location": location[0], "time": time_response.json()}
)
else:
return render(request, "500.html")
# If a location is NOT found, return the error page
else:
return render(request, "fail.html")

except Exception as error:
return render(request, "500.html")