基于Django类的视图访问传递的参数

时间:2016-10-11 21:44:54

标签: django django-views

如何将传递的值记录/打印到基于类的视图?

这是我的班级

class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectForm

我尝试将以下内容附加到课程中,但我没有在控制台中看到任何内容。

def get(self, request, *args, **kwargs):
    logging.info(request['name'])

我无法弄清楚我在这里做错了什么

1 个答案:

答案 0 :(得分:2)

使用self.argsself.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,一个查看标准CBV的方法和属性的好网站,向我们展示了为什么会这样。从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方法的解压缩args和kwargs存储为类属性,并且可以在任何后初始化方法中使用。

相关问题