can't connect details.html to index.html in django

Viewed 59

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'),
    
]

this is a django website where the index creates the link and by clicking on the hyperlink it takes me to the details page

but problem whith current code is upon clicking hyperlink it does not take me to the details page , is something wrong with the urls.py or views.py ?

2 Answers

use name of view as url insted of raw url path

use this "{% url 'details' item.id %}"

Try to use this in your template :-

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

Also change your urls into this :-

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'),

]

Note :- At the place of your_app_name, place the name of your app that you've created.

If any error occur then comment it

Related