Programming Examples

Django program Displaying Data from the Database


Create Django program Displaying Data from the Database.

from django.db import models

models.py

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    def __str__(self):
        return self.title
views.py
from django.shortcuts import render
from .models import Book
def book_list(request):
    books = Book.objects.all()
    return render(request, 'books/book_list.html', {'books': books})
templates/books/book_list.html:
 



    Book List


    

Book List

   
            {% for book in books %}            
  • {{ book.title }} by {{ book.author }}
  •         {% endfor %}    
urls.py
from django.urls import path
from .views import book_list
urlpatterns = [
    path('books/', book_list, name='book_list'),
]
Output

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz