Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update views.py #206

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
35 changes: 28 additions & 7 deletions codershq/dashboard/views.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,43 @@
import requests
from django.shortcuts import redirect, render
from django.http import HttpResponse

# Reddit API URL
news_url = "https://www.reddit.com/r/programming/.json"


def index(request):
"""
Redirects to login page if the user is not authenticated.
"""
if not request.user.is_authenticated:
return redirect("/accounts/login/")
return redirect("/accounts/login/")
# return render(request, "pages/dashboard.html")
return render(request, "pages/dashboard.html")


def landing(request):
"""
Renders the welcome landing page.
"""
return render(request, "pages/welcome.html")


def news(request):
resp = requests.get(url=news_url, headers={"User-agent": "your bot 0.1"})
body = resp.json()
context = {"body": body["data"]["children"]}
return render(request, "dashboard/news.html", context)
"""
Fetches news from Reddit's programming subreddit and renders the news page.
"""
try:
# Fetch data from Reddit
resp = requests.get(news_url, headers={"User-agent": "your bot 0.1"})
resp.raise_for_status() # Raises an HTTPError for bad responses

# Parse the JSON response
body = resp.json()
context = {
"body": body["data"]["children"]
}

return render(request, "dashboard/news.html", context)

except requests.exceptions.RequestException as e:
# If there is any issue with the request, return an error message
return HttpResponse(f"An error occurred while fetching news: {str(e)}", status=500)