How can Django achieve displaying databases on a webpage?
In Django, you can achieve database web display by following these steps:
- To define a model class: First, you need to define a model class in Django’s models.py file to describe the table structure and field properties in the database.
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
def __str__(self):
return self.title
- Migrate the database: Run the following command to migrate the database and create the corresponding table structure.
python manage.py makemigrations
python manage.py migrate
- Create a view function: Create a view function in the views.py file to handle the corresponding requests and fetch data from the database.
from django.shortcuts import render
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books': books})
- Create a template file: Create a book_list.html template file in the templates directory for rendering web pages.
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} - {{ book.author }} - {{ book.publication_date }}</li>
{% endfor %}
</ul>
</body>
</html>
- Set up URL routing: Configure URL routing in the urls.py file to map requests to the corresponding view functions.
from django.urls import path
from .views import book_list
urlpatterns = [
path('books/', book_list, name='book_list'),
]
That way, when you visit http://localhost:8000/books/, you will be able to see the list of books retrieved from the database.