指定通用视图的上下文对象名称

时间:2013-06-11 14:44:13

标签: django django-generic-views

我很难为django的基于通用类的视图设置上下文对象名称。

class FictiveCreateView(generic.CreateView):
    context_object_name = 'fictive_form'
    form_class = forms.FictiveForm
    template_name = 'fictive/create_fictive.html'

    def get_context_data(self, **kwargs):
        context = super(generic.CreateView, self).get_context_data(**kwargs)
        print context

我认为设置context_object_name = 'fictive_form'会改变上下文对象的名称。 原来它只是给出一个空对象:

{'fictive_form': None, 'form': <fictive.forms.FictiveForm object at 0x7f925807a9d0>, u'view': <fictive.views.FictiveCreateView object at 0x7f925807aa50>}

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

context_object_name适用于您的模型

class FictiveCreateView(generic.CreateView):
    context_object_name = 'fictive_form'
    form_class = forms.FictiveForm
    template_name = 'fictive/create_fictive.html'
    model = YourModel

    def get_context_data(self, **kwargs):
        context = super(generic.CreateView, self).get_context_data(**kwargs)
        print context

在您的模板中,fictive_form现在是YourModel的对象