django如何获取数据库数据并在单独的页面上显示

问题描述 投票:0回答:1

我正在为我的网络开发课程开发一个活动跟踪器,我们正在与 django 合作。我正在尝试添加一个页面,通过将其 id 传递到 url 中,在单独的页面上显示活动详细信息,以显示特定于该数据库对象的活动信息(类似于网站上的新闻文章)

我认为问题出在我的观点页面。我需要帮助编写如何正确从数据库获取信息以传递到 html 表单。页面加载正常,id 附加到 url,但没有显示任何信息

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")

这是我的 html 页面(如有必要,可以重命名传递的数据) 活动.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(如果需要查看)

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)

和我的 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")
]

我无法添加课堂上未讨论的任何额外的库或模块,因此我无法对此进行太多更改。感谢您的帮助!

尝试传递不同的参数和名称,但没有任何帮助

django django-models django-views django-templates
1个回答
0
投票

获取ID后,你没有将活动模型传递给视图activity.html。

© www.soinside.com 2019 - 2024. All rights reserved.