Thursday, September 17, 2020

Show database table data on frontend

Here, courses is the app folder. 

courses\views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Course

def index(request):
 courses = Course.objects #--> fetch the model objects from DB
 return render(request,'courses/index.html',{'courses':courses})


courses\templates\courses\index.html

--

<h1>Courses</h1>

{% for course in courses.all %}

{{ course.summary }}

<br>

{% endfor %}


---

In a simple manner, you can show all objects in the view using 

Class Another(View):

  courses = Course.objects.all()

  output = f"We have {len(courses)} that many books in DB"

  def get(self,request):

     return HttpResponse(self.output)



Class Another1(View):

  courses = Course.objects.filter(is_published=True)

  #course = Course.objects.get(id=2)

  output=''

  for course in courses:

    output += f"We have {course.title} that with ID {course.id}<br>"

  def get(self,request):

     return HttpResponse(self.output)

No comments:

Post a Comment