index应用代码
时间: 2024-02-15 12:05:21 浏览: 14
这里是一个简单的 index 应用的代码示例,使用 Django 框架:
```python
# views.py
from django.shortcuts import render
from .models import Book
def index(request):
books = Book.objects.all()
return render(request, 'index.html', {'books': books})
```
```html
<!-- index.html -->
{% extends 'base.html' %}
{% block content %}
<h1>Books Index</h1>
<form action="{% url 'index' %}" method="GET">
<input type="text" name="query" placeholder="Search...">
<button type="submit">Search</button>
</form>
<ul>
{% for book in books %}
<li>
<a href="{% url 'book_detail' book.id %}">
{{ book.title }} by {{ book.author }}
</a>
</li>
{% empty %}
<li>No books found.</li>
{% endfor %}
</ul>
{% endblock %}
```
```python
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
publisher = models.CharField(max_length=255)
summary = models.TextField()
pub_date = models.DateField()
def __str__(self):
return self.title
```
这个示例包括一个视图函数 `index`,它从数据库中获取所有书籍,并将它们传递给模板文件 `index.html`。模板文件显示了一个搜索框,用户可以输入关键字来缩小搜索范围。然后,模板文件列出了所有书籍的名称和作者,并提供了一个链接,用户可以点击链接以查看更多详细信息。