Получение определенного элемента из таблицы по щелчку мыши в Django MVT
У меня есть таблица товаров, отображаемая в моем шаблоне с помощью jinja loop.
`
{% extends 'base.html' %}
{% load static %}
{% block css %}
<link rel="stylesheet" href= "{% static 'css\store.css' %}" >
{% endblock %}
{%block content%}
{% load static %}
<div class="secondnav">
<a class="nav-item" href="construction"> Figures </a>
<a class="nav-item" href="construction"> Manga </a>
<a class="nav-item" href="construction"> Clothes </a>
</div>
{% 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 %}
{% endblock %}
`
Я хочу щелкнуть на одном экземпляре, показанном в цикле, и получить id этого экземпляра в моем представлении 'item'. Мое представление 'item' выводит страницу только одного экземпляра. При вводе его в url в браузере он выдает нужную страницу с контекстом. Вот представление
`
def store(request):
products = Product.objects.all()
return render(request, 'store.html', {'products': products}) ;
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 })
`
и вот приложение urls.py
`
from django.urls import path
from . import views
app_name = "login"
urlpatterns = [
path("", views.home, name='home'),
path("login", views.login, name="login"),
path("register", views.register, name="register"),
path("profile", views.profile, name="profile"),
path("logout", views.logout, name="logout"),
path("store/", views.store, name="store"),
path("commissions", views.commissions, name="commissions"),
path("port", views.port, name="port"),
path("item/<int:item_id>", views.item, name="item"),
path("construction", views.construction, name="construction"),
]
`
Теперь я получаю ошибку, когда нажимаю открыть магазин
Exception Type: NoReverseMatch Exception Value: Reverse for 'item' not found. 'item' is not a valid view function or pattern name.
Я просмотрел множество StackOverflow и пришел к "дублирующей ссылке" для этой ошибки. Кто-то там сказал
'Часть аргументов обычно представляет собой объект из ваших моделей. Не забудьте добавить его в контекст в представлении. В противном случае ссылка на объект в шаблоне будет пустой и поэтому не будет соответствовать url с object_id.'
Я думаю, что проблема может быть в этом, но я не уверен. Кто-то другой сказал
'
Обратите внимание на разные аргументы, передаваемые между reverse() и redirect(), например:
url(r"^some_app/(?P<some_id>\d+)/$", some_view_function, name="some_view")
будет работать с:
reverse("some_view", kwargs={"some_id": my_id})
и:
redirect("some_view", some_id=my_id)
но не с:
reverse("some_view", some_id=my_id)
и:
redirect("some_view", kwargs={"some_id": my_id})
'
Поскольку это NoReverseMatch, возможно, я должен использовать обратное соответствие? Но я не уверен, как я смогу вписать это в мои текущие представления.