在Python Django中,可以通过以下步骤将模型的数据传递到管理默认起始页(index.html):
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
from django.contrib import admin
from .models import Book
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author') # 自定义显示的字段
admin.site.register(Book, BookAdmin)
from django.shortcuts import render
from .models import Book
def index(request):
books = Book.objects.all() # 获取所有书籍对象
return render(request, 'index.html', {'books': books})
from django.urls import path
from .views import index
urlpatterns = [
path('', index, name='index'),
]
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} - {{ book.author }}</li>
{% endfor %}
</ul>
</body>
</html>
以上步骤完成后,当你访问默认起始页(index.html)时,Django将会从数据库中获取所有的书籍对象,并将它们传递到index.html页面进行展示。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云