【问题标题】:Specifying context object names of generic views指定通用视图的上下文对象名称
【发布时间】:2013-06-11 14:44:12
【问题描述】:

我很难为 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>}

我在这里错过了什么?

【问题讨论】:

    标签: django django-generic-views


    【解决方案1】:

    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 的一个对象

    【讨论】:

    • 不,fiction_form 仍然是 None。我不明白为什么 CreateView 无论如何都需要模型。不过使用表单上下文变量效果很好。
    猜你喜欢
    • 2013-02-22
    • 2013-03-14
    • 2010-10-15
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2011-08-14
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多