【问题标题】:I want to make it so that each product will have a link, and the link will link to a page with the product's info我想让每个产品都有一个链接,该链接将链接到包含产品信息的页面
【发布时间】:2020-07-18 23:00:52
【问题描述】:

我正在做一个 django 项目。

这是我的models.py 文件:

class Product(request):
    name = models.CharField(max_length=255)
    cost = models.FloatField(max_length=255)
    info = models.CharField(max_length=2000)

这是我的views.py 文件:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Product

def index(request):
    products = Product.objects.all()
    return render(request, 'index.html',
                  {'products': products})

# I know the below is incorrect, but I don't know how to correct it.

def information(request):
    info = Product.objects.all()
    return HttpResponse(info[products.index(product)].info)

这是我的index.html 文件:

{% for product in products %}
    <l1>{{product.name}} ${{ product.price }}</li>
{% endfor %}

我想让每个产品都有一个链接,该链接将链接到包含产品信息的页面。我怎样才能动态地做到这一点?

谢谢。

【问题讨论】:

    标签: django django-models django-views django-templates


    【解决方案1】:

    我的建议是使用 django 内置的通用视图,它们非常有用。

    首先,您需要一个ListView 来列出您的所有产品,例如:

    from django.views import generic
    class ProductList(generic.ListView):
        model = models.Product
        template_name = 'products/product_list.html'
        context_object_name = 'product_list'
    

    然后是DetailView

    class ProductDetail(generic.DetailView):
        model = models.Product
        template_name = 'products/product_detail.html'
        context_object_name = 'product'
    

    现在在您的列表模板中,您可以执行以下操作:

    {% if product_list %}
    {% for product in product_list %}
    <a href="{% url 'products:detail' pk=product.pk %}"> {{product.name}} </a>
    {% endfor %}
    {% endif %}
    

    在您的详细信息模板上,您可以执行类似的操作来显示例如成本和信息。显然这只是一个示例,您必须对其进行更改以满足您的需要。但这应该可以帮助您入门。有关更多信息,您还可以参考相关文档:

    https://docs.djangoproject.com/en/3.0/ref/class-based-views/generic-display/

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多