使用任何通用的基於類的視圖self.args
和self.kwargs
作品。
class ProjectCreateView(CreateView):
model = Project
form_class = ProjectForm
def get(self, request, *args, **kwargs):
project_name = self.kwargs.get('project_name', None)
# Do something
return super(ProjectUpdateView, self).get(request, *args, **kwargs)
在Classy Class Based Views來看,用於查看方法和屬性標準CBVS一個偉大的網站,告訴我們這是爲什麼。看看這個從TemplateView source code:
@classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
的解壓指定參數和傳遞給view
方法kwargs存儲爲類的屬性,並可以在任何初始化後的方法。