Python 带括号的Django CVB属性
我正试着用Django Unreleased这本书来学习Django。在第9章中,作者将表单显示方法重写为基于类的视图(CBV)。我试图理解为什么在调用class属性时使用了一组括号。我假设是这样,因为class属性将存储一个表单对象,但我想进一步了解它Python 带括号的Django CVB属性,python,django,Python,Django,我正试着用Django Unreleased这本书来学习Django。在第9章中,作者将表单显示方法重写为基于类的视图(CBV)。我试图理解为什么在调用class属性时使用了一组括号。我假设是这样,因为class属性将存储一个表单对象,但我想进一步了解它 from django.shortcuts import render, get_object_or_404, redirect from .models import Tag, Startup from .forms import TagFo
from django.shortcuts import render, get_object_or_404, redirect
from .models import Tag, Startup
from .forms import TagForm
from django.views.generic import View
class PostCreate(View):
form_class = PostForm
template_name = 'blog/post_form.html'
def get(self, request):
return render(
request,
self.template_name,
{'form': self.form_class()})
def post(self, request):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_post = bound_form.save()
return redirect(new_post)
else:
return render(
request,
self.template_name,{'form': bound_form})
如你所见,在14行代码是
{'form': self.form_class()})
self.template_name,
但在最后一行,代码是
{'form': self.form_class()})
self.template_name,
我不明白作者为什么在第一个类属性上使用括号而不是在第二个类属性上使用括号。你能解释一下吗
多谢各位
我不明白作者为什么在第一个类属性上使用括号而不是在第二个类属性上使用括号。你能解释一下吗
在get
中,作者使用了self.form\u class()
即实际上PostForm()
,因为self.form\u class
只是对PostForm
类的引用,所以当self.form\u class
带有括号时,即self.form\u class()
它是PostForm
的实例,没有传递任何参数
及
在post
方法中,作者将request.post
传递给self.form\u类
,该类再次只是引用PostForm
,因此现在它是PostForm(request.post)
,并将其分配给变量bound\u form
,因此bound\u form
按原样传递
希望这能消除你的困惑