Reputation: 12230
How can I log / print passed values to class based view?
Here is my class
class ProjectCreateView(CreateView):
model = Project
form_class = ProjectForm
I have tried appending the following to the class but I'm not seeing anything printed in the console.
def get(self, request, *args, **kwargs):
logging.info(request['name'])
I can't figure out what I'm doing wrong here
Upvotes: 0
Views: 1376
Reputation: 7626
Using self.args
and self.kwargs
works in any generic class-based-view.
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)
Looking at Classy Class Based Views, a great site for viewing the methods and attributes standard CBVs, shows us why this is. Take a look at this from the 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)
The unpacked args and kwargs passed to the view
method are stored as class attributes and available at any post-initialization methods.
Upvotes: 2