【问题标题】:how to retrive the object data by using it's id in Django in template file (HTML file)?如何在模板文件(HTML 文件)中使用 Django 中的 id 来检索对象数据?
【发布时间】:2016-07-30 16:38:36
【问题描述】:

我有一个这样的模板文件(index.html)

  1. 汽车项目1
  2. 汽车项目2
  3. 汽车项目3

当单击它们中的每一个时,我们会重定向到一个带有名为 {{ Car_id }} 的变量的模板文件 (details.html),我想在此模板文件中显示有关此对象的详细信息。如何从模板文件中的数据库中检索对象?

这里是views.py:

from django.shortcuts import render
from .models import Car

def index(request):
    latest_car_list = Car.objects.order_by('-placketName')[:5]
    context = {
        'latest_car_list': latest_car_list,
    }
    return render(request, 'CarBank/index.html', context)

def detail(request, car_id):
    context = {
        'car_id': car_id
    }
    return render(request, 'CarBank/details.html', context)

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    如果你使用的是 Django 自己的模板系统:

    您可以访问已传递到上下文字典(在您的视图文件中)的变量,只需在模板文件中使用{{ variable_name }} 标记即可。

    更新:

    您需要在视图中从数据库中检索对象,就像在 index 视图中那样。如果您想在detail 视图中从您的数据库中检索单个对象,您可以这样做:

    def detail(request, car_id):
        car = Car.objects.get(pk=car_id)
        context = {
            'car': car
        }
        return render(request, 'CarBank/details.html', context)
    

    然后只需在模板中调用{{ car }}

    阅读更多here

    【讨论】:

    • 嗨,伙计!我知道。但我不知道如何通过这个变量 {{ Car_id }} 从数据库中检索数据。
    猜你喜欢
    • 2013-03-28
    • 2019-05-03
    • 2014-12-03
    • 2013-03-18
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    相关资源
    最近更新 更多