如何调用urls.py从Django的循环中获取值

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

在索引页面上,我有一个图库。当某人单击图像时,它应该在另一页上显示更多信息以及更多照片。所有这些都使用for循环从MySQL数据库加载。我无法从数据库中获取单击图像的详细信息。它加载所有数据

此页面的过程就像一个新闻网站-所有新闻都是从循环中加载的。如果某人单击新闻项,则应该只显示有关该新闻项的详细信息。

下面是我的index.html页面,还有我的urls.pyviews.py源代码。

我正在将Python和Django与MySQL配合使用;所有最新版本。

[Home pagesource code of my images gallery

{% for x in destination %}
<!-- Destination -->
<a href="destination" id="{{x.id}}"><div class="destination item" >
    <div class="destination_image">
        <img src="{{x.img.url}}" alt="">
        {% if x.offer %}
        <div class="spec_offer text-center"><a >Special Offer</a></div>
        {% endif %}
    </div>
    <div class="destination_content">
        <div class="destination_title"><a href="">{{x.name}}</a></div>
        <div class="destination_subtitle"><p>{{x.short_description}}</p></div>
        <div class="destination_price">From ${{x.price}}</div>
    </div>
</div></a>

{% endfor %}
from . import views
from django.urls import path

urlpatterns = [
    path('destination', views.destination, name='destination'),
    path('', views.index, name='index')
]
from django.shortcuts import render
from .models import Destination


def destination(request):
    dest = Destination
    return render(request, 'destination.html', {'sub_destination': dest})
python django django-urls
1个回答
0
投票

您可以使用Reverse resolution of URLs。只需在urls.py中添加另一个网址格式:

urlpatterns = [
    path('destination/<int:dest>/', views.destination_content, name='destination_content'),
    # ...
]

并像这样在模板中使用它:

    <div class="destination_content">
        <div class="destination_title"><a href="{% url 'destination_content' x.id %}">{{x.name}}</a></div>
        ...
    </div>

NOTE:您必须在destination_content]中定义views.py函数

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