python - 无法在 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 有问题吗?
解决方案
尝试在您的模板中使用它:-
{% 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的位置,放置您创建的应用程序的名称。
如果出现任何错误,请评论它
推荐阅读
- python - BiqQuery 将“字节”列拆分为行
- python - 我的第一个重命名文件名项目的问题
- excel - 如何从 Google 电子表格到 Excel 2016 获取 IFERROR+INDEX+MATCH
- c++ - Open3D 函数中的特征密集存储分段错误
- python-3.x - 如何计算数据框列中 >=3 个连续 1 值的出现次数
- linkedin - 包含特定链接的Linkedin帖子未发布
- json - 将 json 数据发送到新屏幕 Flutter
- reactjs - 如何从 Apollo 客户端的缓存中读取突变响应?
- javascript - 在 Django 中使用 Axios 和 CORS 获取 POST 请求的错误请求并做出反应
- java - 在 MapBox Android 中模拟用户位置