I am working on an activity tracker for my web development class and we're working with django. I'm trying to add a page that shows the activity details on a separate page by passing it's id into the url to display the activity info specific to that database object (similar to news articles on websites)
I think the problem lies in my views page. I need help writing how to properly get the info from the database to pass over to the html form. The page loads fine with the id attached to the url but no info is showing
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpRequest
from . models import Activity
# Create your views here.
def index(request: HttpRequest):
activites = Activity.objects.all()
return render(request, "activity/index.html", {"activites" : activites})
def new_activity(request: HttpRequest):
if request.method == 'POST':
params = request.POST
activity = Activity(
activity_name = params.get("activity_name")
)
activity.save()
return redirect("/")
return render(request, "activity/new_activity.html")
def activity(request: HttpRequest, id):
id = Activity.objects.get(id=id)
return render(request, "activity/activity.html")
Here's what I have for the html page (open to renaming the data passed if necessary) activity.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ activity.activity_name }}</h1>
</body>
</html>
models.py (if needed to look at)
from django.db import models
from datetime import timedelta
# Create your models here.
class Activity(models.Model):
id = models.BigAutoField(primary_key=True)
activity_name = models.TextField()
def time_spent(self):
delta = timedelta()
for timelog in self.timelog_set.all():
delta += (timelog.end_time - timelog.start_time)
return str(delta)
class TimeLog(models.Model):
id = models.BigAutoField(primary_key=True)
start_time = models.TimeField()
end_time = models.TimeField()
activity = models.ForeignKey("Activity", related_name="time_logs", on_delete=models.CASCADE)
and my urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("new_activity/", views.new_activity, name="new_activity"),
path("activity/<int:id>", views.activity, name="activity")
]
I can't add any extra libraries or modules that wasn't discussed in class so I can't change this too much. Appreciate the help!
Tried passing different arguments and names but nothing helped
you did not send context.
def activity(request: HttpRequest, id):
obj = Activity.objects.get(id=id)
return render(request, "activity/activity.html" {'activity': obj})
# activity.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ activity.activity_name }}</h1>
</body>
</html>