如何使基于类的视图从URL接受参数或在URLconf中硬编码

时间:2013-08-12 20:17:39

标签: python django django-class-based-views

我正在研究一个基于类的通用视图,它将模型名称作为参数并处理该模型名称以获取更多参数。当我将模型名称硬编码到URLconf中的条目时,我工作得很好:

url(r'^generic/', ResultCreateView.as_view(model = 'SomeTask'))

基于类视图的片段:

class ResultCreateView(CreateView):
    model = None #this is here, expecting to be overwritten, because otherwise I get an error saying I can't pass in the 'model' kwarg above because 'model' is not already an attribute of the class
    def __init__(self,*args, **kwargs):
        self.model = get_model_object_from_modelname(kwargs['model'])
        self.form_class = my_custom_function_to_generate_a_formclass(self.model)
        self.template_name = self.model.template #template_name is an attribute I set on the model class
        return super(ResultCreateView,self).__init__(*args, **kwargs)

当我尝试通过url切换到传递model参数时,即:

url(r'^tasks/(?P<model>\w+)$', ResultCreateView.as_view())

我的自定义 init 方法不再有效。我明白了:

  

ResultCreateView缺少查询集。定义ResultCreateView.model,ResultCreateView.queryset或覆盖ResultCreateView.get_queryset()

我无法弄清楚'model'参数从URL模式传递到视图类的位置。理想情况下,我希望能够使这个视图在任何一种情况下工作(URLconf中的硬编码参数或URL模式中的参数)但我不知道在哪里放置进行处理的代码,以便它在正确的时间发生。放置该代码的正确位置在哪里,或者我应该使用另一种方法?

编辑:(其他并发症:我需要用装饰器来装饰视图,将'model'作为参数。)

1 个答案:

答案 0 :(得分:0)

这些参数将传递给实际的请求处理程序方法,而不是视图的__init__方法。所以,如果有GET请求:

class ResultCreateView(CreateView):
    model = None

    def get(self, request, model_name):
        self.model = get_model_object_from_modelname(model_name)
        self.form_class = my_custom_function_to_generate_a_formclass(self.model)
        self.template_name = self.model.template #template_name is an attribute I set on the model class
        return super(ResultCreateView,self).get(request, model_name)