【问题标题】:can't connect details.html to index.html in django无法在 django 中将 details.html 连接到 index.html
【发布时间】:2021-05-22 07:19:54
【问题描述】:

index.html

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

detail.html

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

views.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))

urls.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 有问题吗?

【问题讨论】:

    标签: python html django database


    【解决方案1】:

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

     {% 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 的位置,放置您创建的应用的名称。

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

    【讨论】:

    • 现在在 /foodmenu/ 错误处给出 NoReverseMatch
    • 你的app name 是什么?
    • appname 是 foodmenu
    • 然后把url改成这个&lt;a href="{% url 'foodmenu:details' item.id %}"&gt;{{item.item_name}}&lt;/a&gt;
    • template 部分更新了我的答案。
    【解决方案2】:

    使用视图名称作为原始 url 路径的 url

    使用这个“{% url 'details' item.id %}”

    【讨论】:

    • 先生,您能告诉我在哪里添加“{% url 'details' item.id %}”以及在哪个文件中,谢谢
    猜你喜欢
    • 2020-06-19
    • 2018-05-13
    • 2022-09-28
    • 2021-02-05
    • 2019-05-22
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2016-05-02
    相关资源
    最近更新 更多