django写一个完整的后端程序
时间: 2023-10-07 15:14:14 浏览: 110
基于django制作的一个后台管理系统
以下是一个简单的Django后端程序示例,它包括了一个视图函数、一个模型和一个表单类:
在`models.py`中定义模型:
```python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_date = models.DateField()
def __str__(self):
return self.title
```
在`forms.py`中定义表单类:
```python
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'published_date']
```
在`views.py`中定义视图函数:
```python
from django.shortcuts import render, redirect
from .models import Book
from .forms import BookForm
def book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books': books})
def add_book(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
return redirect('book_list')
else:
form = BookForm()
return render(request, 'add_book.html', {'form': form})
```
在`urls.py`中定义URL路由:
```python
from django.urls import path
from .views import book_list, add_book
urlpatterns = [
path('books/', book_list, name='book_list'),
path('books/add/', add_book, name='add_book'),
]
```
最后,在模板中使用上述视图函数所返回的数据:
`book_list.html`:
```html
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }} (Published: {{ book.published_date }})</li>
{% endfor %}
</ul>
<a href="{% url 'add_book' %}">Add a Book</a>
</body>
</html>
```
`add_book.html`:
```html
<!DOCTYPE html>
<html>
<head>
<title>Add a Book</title>
</head>
<body>
<h1>Add a Book</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
</body>
</html>
```
注意,这个示例程序并没有包括任何数据库配置。你需要在`settings.py`文件中配置数据库连接,以便在使用模型时能够连接到数据库。此外,你还需要在`urls.py`文件中包含该应用程序的URL路由,以便Django能够找到和调用视图函数。
阅读全文