首页 > 解决方案 > 无法在 django 中将 details.html 连接到 index.html

问题描述

索引.html

 {% for item in item_list%}
    <ul>
        <li>
            <a href="/foodmenu/{{item.id}}">{{item.id}} -- {{item.item_name}}</a>
        </li>
    </ul>
    {% endfor %}

详细信息.html

<h1>{{item.item_name}}</h1>
<h2>{{item.item_desc}}</h2>
<h3>{{item.item_price}}</h3>

视图.py

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .models import item
from django.template import loader

# Create your views here.

def index(request):
    item_list = item.objects.all()
    template_name = loader.get_template('foodmenu/index.html')
    context = {
        'item_list':item_list,
    }
    return HttpResponse(template_name.render(context,request))




def detail(request,item_id):
    item = Item.objects.get(pk=item_id)
    template_name = loader.get_template('foodmenu/detail.html')
    context = {
        'item':item,
    }
    return HttpResponse(template_name.render(context,request))

网址.py

from . import views
from django.conf.urls import url


urlpatterns = [
    #foodmenu/
    url("foodmenu", views.index,name='index'),
    #foodmenu/1
    url("<int:item_id>/", views.detail,name='detail'),
    
]

这是一个 django 网站,其中的索引创建了链接,通过单击超链接,我会转到详细信息页面

但是当前代码的问题是在单击超链接时它不会将我带到详细信息页面,urls.py 或views.py 有问题吗?

标签: pythonhtmldjangodatabase

解决方案


尝试在您的模板中使用它:-

 {% for item in item_list%}
    <ul>
        <li>
        <a href="{% url 'foodmenu:details' item.id %}">{{item.item_name}}</a>
        </li>
    </ul>
  {% endfor %}

还将您的网址更改为:-

from . import views
from django.urls import path

app_name = 'your_app_name'

urlpatterns = [
    #foodmenu/
    path('', views.index,name='index'),
    #foodmenu/1
    path('<int:item_id>/', views.detail,name='detail'),

]

注意:- 在your_app_name的位置,放置您创建的应用程序的名称。

如果出现任何错误,请评论它


推荐阅读