DJango Как выбрать определенный элемент из таблицы базы данных в html
У меня есть страница магазина, которая получает записи из таблицы Products. Она показывает товары по порядку в том же формате бесконечно, сколько их в таблице.
`
{% for product in products %}
<div class="container2">
<div href="item" class= 'product-item'>
<div class= 'image-cont'>
<a href="item"><img class='product-image'src = '{{product.product_picture.url}}' alt="" ></a>
</div>
{% if product.offer != 0 %}
<div class= 'offer-banner' >
<a href="item">Special Offer</a>
</div>
{% endif %}
</div>
<div href="item" class="product-content">
<div href="item" class="product-title">
<a href="item" >{{product.name}}</a>
</div>
<div class="product-price">
<a href="item" >${{product.price}}</a>
</div>
<br>
<div class="product-desc">
<a href="item" >{{product.desc}}</a>
</div>
<br>
<div class="product-userpfp">
<a href="#" ><img src='{{product.userpfp.url}}'></a>
</div>
<br>
<div class="product-poster-name">
<a href="#" >{{product.username}}</a>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
`
Я хочу иметь возможность нажать на любой товар из товаров и получить страницу с конкретным товаром, на который я нажал. Это моя страница товара.
`
{`% extends 'base.html' %}
{% load static %}
{% block css %}
<link rel="stylesheet" href= "{% static 'css\item.css' %}" >
{% endblock %}
{%block content%}
{% load static %}
<h1>Item</h1>
<h3>{{item.name}}</h3>
{% endblock %}`
`
Проблема должна быть внутри файла view.py
`
def item(request):
item = Product.objects.select_related()
return render(request, "item.html", {"item": item })
def store(request):
products = Product.objects.all()
return render(request, 'store.html', {'products': products}) ;
`
Функция магазина работает. Но функция item не работает. Я предполагаю, что 'select_related' может быть неправильным инструментом для использования.
Я пробовал менять инструмент select_related на несколько разных, но боялся, что как-то испорчу свою таблицу, поэтому обращаюсь за помощью, спасибо.
Для выбора конкретного элемента из таблицы базы данных в Django можно использовать метод get на модели Product. Этот метод принимает в качестве аргумента первичный ключ элемента, который вы хотите получить, и возвращает соответствующий элемент.
Вот как вы можете обновить представление элемента, чтобы использовать метод get для получения определенного элемента:
def item(request, item_id):
# Get the item with the given id
item = Product.objects.get(id=item_id)
return render(request, "item.html", {"item": item })
Затем, в шаблоне store.html, вы можете передать id каждого товара в представление товара, когда пользователь нажимает на товар. Это можно сделать, используя тег шаблона url и передавая id товара в качестве аргумента представлению элемента:
{% for product in products %}
<div class="container2">
<div href="item" class= 'product-item'>
<div class= 'image-cont'>
{# Pass the id of the product to the item view when the user clicks on the product #}
<a href="{% url 'item' product.id %}"><img class='product-image'src = '{{product.product_picture.url}}' alt="" ></a>
</div>
{% if product.offer != 0 %}
<div class= 'offer-banner' >
{# Pass the id of the product to the item view when the user clicks on the offer banner #}
<a href="{% url 'item' product.id %}">Special Offer</a>
</div>
{% endif %}
</div>
<div href="item" class="product-content">
<div href="item" class="product-title">
{# Pass the id of the product to the item view when the user clicks on the product title #}
<a href="{% url 'item' product.id %}" >{{product.name}}</a>
</div>
<div class="product-price">
{# Pass the id of the product to the item view when the user clicks on the product price #}
<a href="{% url 'item' product.id %}" >${{product.price}}</a>
</div>
<br>
<div class="product-desc">
{# Pass the id of the product to the item view when the user clicks on the product description #}
<a href="{% url 'item' product.id %}" >{{product.desc}}</a>
</div>
<br>
<div class="product-userpfp">
{# Pass the id of the product to the item view when the user clicks on the user's profile picture #}
<a href="{% url 'item' product.id %}" ><img src='{{product.userpfp.url}}'></a>
</div>
<br>
<div class="product-poster-name">
{# Pass the id of the product to the item view when the user clicks on the user's name #}
<a href"{% url 'item' product.id %}" >{{product.username}}</a>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
В шаблоне item.html вы можете отобразить детали выбранного товара, обратившись к свойствам объекта item, который был передан в шаблон:
{`% extends 'base.html' %}
{% load static %}
{% block css %}
<link rel="stylesheet" href= "{% static 'css\item.css' %}" >
{% endblock %}
{%block content%}
{% load static %}
<h1>Item</h1>
{# Display the name of the item #}
<h3>{{item.name}}</h3>
{# Display the other details of the item here #}
{% endblock %}
Надеюсь, это поможет!
Предполагая, что вы передаете product_id на страницу товара при нажатии на него, вам нужно передать этот product_id в функцию item и переписать код так,
def item(request):
item = Product.objects.select_related('item').get(id=product_id)
return render(request, "item.html", {"item": item })