Tuesday, January 3, 2023

How to show all records in a model and individual record using pk

 views.py

----


from django.shortcuts import render

from .models import Notes

from django.http import Http404


def list(request):

  all_notes = Notes.objects.all()

  return render(request,'notes/notes_list.html',{'notes': all_notes})


def detail(request, pk):

  try:

   note = Notes.objects.get(pk=pk)

  except Notes.DoesNotExist:

   raise Http404("Note doesn't exist")

  return render(request,'notes/notes_detail.html',{'notes': note})



urls.py

----

from django.urls import path

from . import views


urlpatterns = [

 path('notes',views.list),

 path('notes/<int:pk>',views.detail),

]



main urls.py

---------

urlpatterns=[

path('smart/',include('notes.urls')),

]


notes/templates/notes/notes_list.html

---

<html>

<h1>These are the notes:</h1>

 <ul>

   {% for note in notes %}

    <li>{{note.title}}</li>

   {% endfor % }

 </ul>

</html>


http://localhost:8000/smart/notes


notes_detail.html

----

<html>

<h1>{{note.title}}</h1>

<p>{{note.text}}</p>

</html>


http://localhost:8000/smart/notes/1


No comments:

Post a Comment