如何在 ModelForm 中使用 CreateView [英] How do I use CreateView with a ModelForm
问题描述
当我提交表单时,我的类 AuthorCreateForm 中出现错误.名称错误self 未定义
I get an error in my class AuthorCreateForm when I submit my form. NameError self is not defined
如何使用 CreateForm?
How do I use a CreateForm?
我在 Author.py 文件中创建了一个类
I have created a class in my Author.py file
from django.views.generic import TemplateView, ListView, CreateView
from books.models import Author, Publisher, Book
from books.forms import AuthorForm
class AuthorCreateView(CreateView):
objAuthorForm = AuthorForm(self.request.POST)
if(objAuthorForm.save()):
success = "Form saved!"
else:
error = "There was an error!"
我有一个提交给/Author/Create
and I have a html template which submits to /Author/Create
我的 urls.py 中有以下行
and I have the following line in my urls.py
('^authors/create/$', Author.AuthorCreateView.as_view()),
我在此 URL 处呈现表单
I render the form at this URL
('^authors/new/$', TemplateView.as_view(template_name="author_new.html")),
我发现基于类的视图令人困惑,有没有人有关于如何将其用于 CRUD 操作的好教程?
I find the class based views confusing, does anyone have a good tutorial on how to use it for CRUD operations?
谢谢
推荐答案
您遇到的是 python 错误 -- self
未定义.self
通常是指类方法上的类实例本身.
What you have is a python error -- self
is not defined. self
is generally what refers to the class instance itself on class methods.
无论如何,我同意,它是全新的,没有记录.我认为在这一点上查看来源绝对是关键.
Anyways, I agree, it's brand spanking new and not as documented. I think looking at the source is absolutely key at this point.
为了适应基于类的视图,我首先对 django.views.generic.base.View
进行子类化,它只实现了几个方法,即尝试调用类上的函数基于请求方法(post、get、head、-查看源).
To get comfortable with class based views, I'd start by subclassing django.views.generic.base.View
, which implements only a few methods, namely attempting to call a function on the class based on the request method (post, get, head, - look at source).
例如,这是用新的视图类替换视图函数的第一步:
For example, here's the first step to replace view functions with the new view classes:
class MyClassBasedView(View):
def get(self, request):
# behave exactly like old style views
# except this is called only on get request
return http.HttpResponse("Get")
def post(self, request):
return http.HttpResponse("Post")
(r'^foobar/$', MyClassBasedView.as_view())
回到你的具体问题:
TemplateView.as_view()
所做的只是渲染模板 - CreateView
是处理 ModelForms
和模板渲染的几个其他类的组合(TemplateView
).
All TemplateView.as_view()
does is render the template - CreateView
is a combination of several other classes that handle ModelForms
and template rendering (TemplateView
).
所以,对于一个非常基本的例子,查看文档 以了解 CreateView
使用什么类 mixins
.
So, for a very basic example, look to the docs for what class mixins
are used by CreateView
.
我们看到它实现了 TemplateResponseMixin
、ModelFormMixin
和 ProcessFormView
,每个都包含这些类的方法列表.
We see it implements TemplateResponseMixin
, ModelFormMixin
, and ProcessFormView
, each containing a list of methods for those classes.
在最基本的层面上,为 CreateView
的 ModelFormMixin
提供模型或自定义 ModelForm 类 如此处所述.
At the most basic level, provide CreateView
's ModelFormMixin
with the model or custom ModelForm class as documented here.
您的 CreateView
类将类似于以下内容
Your CreateView
class would look something like the following
class AuthorCreateView(CreateView):
form_class = AuthorForm
template_name = 'author_new.html'
success_url = 'success'
设置这 3 个核心属性后,在您的 URL 中调用它.
With those 3 core attributes set, call it in your URLs.
('^authors/create/$', Author.AuthorCreateView.as_view()),
渲染页面,您将看到 ModelForm 作为 form
传递给模板,处理表单验证步骤(传入 request.POST
/re-render if无效),以及调用 form.save()
并重定向到 success_url
.
Render the page and you'll see your ModelForm passed to the template as form
, handling the form validation step (passing in request.POST
/ re-render if invalid), as well as calling form.save()
and redirecting to the success_url
.
要自定义行为,请开始覆盖为 mixins
记录的方法.
To customize behavior, start overriding the methods documented for the mixins
.
请记住,您只需像任何常规视图函数一样从这些方法之一返回 HttpResponse
.
Remember that you simply need to return an HttpResponse
from one of these methods just like any regular view function.
覆盖ModelFormMixin
中记录的form_invalid
示例:
Example overriding form_invalid
documented in ModelFormMixin
:
class AuthorCreateView(CreateView):
form_class = AuthorForm
template_name = 'author_new.html'
success_url = 'success'
def form_invalid(self, form):
return http.HttpResponse("form is invalid.. this is just an HttpResponse object")
<小时>
随着表单变得越来越高级,这种按方法覆盖的方法开始变得非常有用,最终让您可以使用少量代码构建大型表单,只覆盖必要的内容.
This per-method overriding starts becoming extremely useful as your forms grow more advanced and ultimately lets you build huge forms with a handful of lines of code, overriding only what is necessary.
假设你想传递你的表单自定义参数,比如 request
对象(如果你需要访问表单中的用户,这很常见):你只需要覆盖 get_form_kwargs代码>.
Say you want to pass your form custom parameters such as the request
object (very common if you need access to the user in the form): you merely need to override get_form_kwargs
.
class MyFormView(FormView):
def get_form_kwargs(self):
# pass "user" keyword argument with the current user to your form
kwargs = super(MyFormView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
基于类的视图是智能类使用的光辉例子.它给了我一个很好的介绍,可以为我自己的视图和 Python 类构建自己的 mixin.它节省了无数个小时.
Class based views are a shining example of smart class usage. It gave me a great intro towards building my own mixins for views and python classes in general. It is saving countless hours.
哇,这太长了.认为它只是一个指向文档评论的 URL :)
Wow this got long. To think it started as a mere URL to the docs comment :)
这篇关于如何在 ModelForm 中使用 CreateView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!