Django CreateView 用法示例
时间: 2024-01-20 14:02:36 浏览: 100
好的,这是一个Django CreateView的用法示例:
```python
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
description = models.TextField()
# forms.py
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'description']
# views.py
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Book
from .forms import BookForm
class BookCreateView(CreateView):
model = Book
form_class = BookForm
success_url = reverse_lazy('books:list')
template_name = 'book_create.html'
# urls.py
from django.urls import path
from .views import BookCreateView
app_name = 'books'
urlpatterns = [
path('create/', BookCreateView.as_view(), name='create'),
]
# book_create.html
{% extends 'base.html' %}
{% block content %}
<h1>Create Book</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create</button>
</form>
{% endblock %}
```
这个示例中,我们定义了一个Book模型、BookForm表单和BookCreateView视图。BookCreateView继承了Django内置的CreateView视图,使用了Book模型和BookForm表单,重定向到了'books:list' URL,并使用了自定义的book_create.html模板。在模板中,我们使用了Django内置的form.as_p标签来渲染表单。
阅读全文