使用不带表单的 Django CreateView 创建对象
我正在 django 1.3 中使用基于分类的视图,并试图弄清楚如何在不使用表单的情况下创建对象。我不需要任何用户输入来创建对象,但我仍然收到一条错误消息,提示模板丢失。下面是我当前的视图,我尝试对 form_valid 方法进行子类化,但它不起作用。任何帮助将不胜感激。
class ReviewerCreateView(CreateView):
model = Reviewer
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.role = 2
self.object.save()
return HttpResponseRedirect(self.get_success_url())
I am using classed based views with django 1.3 and am trying to figure out how to create an object without using the form. I do not need any user input to create the object but I am still getting an error message that the template is missing. Below is my current view where I have tried to subclass the form_valid method but its not working. Any help would be appreciated.
class ReviewerCreateView(CreateView):
model = Reviewer
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.role = 2
self.object.save()
return HttpResponseRedirect(self.get_success_url())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CreateView 是一种专用视图,其目的是在 GET 上显示表单并验证表单数据并根据 POST 上的表单数据创建新对象。
由于您不需要显示表单并处理表单数据,因此 CreateView 不适合您的工作。
您要么需要一个普通的基于函数的旧视图,或者,如果您更喜欢使用基于类的视图,请从 View 派生并覆盖
get()
或post()
。例如,调整您的示例代码:A CreateView is a specialized view whose purpose is to display a form on GET and validate the form data and create a new object based on the form data on POST.
Since you don't need to display a form and process the form data, a CreateView is not the tool for your job.
You either need a plain old function-based view, or, if you prefer to use a class-based view, derive from View and override
get()
orpost()
. For example, adapting your sample code:我认为如果视图不需要表单,则不需要对表单执行任何明确的操作。
您可以实例化一个 Reviewer 对象。它只是一个Python对象。
I don't believe a view needs to do anything explicit with a form if it does not need one.
You can instantiate a Reviewer object. It's just a python object.