用于将多个数据传递到模板的通用视图

时间:2018-12-10 10:39:25

标签: django django-generic-views

字段值不显示在模板中,仅显示extrainfo。我想同时显示(字段)和(额外信息)值

class CompanyUpdateView(UpdateView):
    model = Company
    fields = ['company_name', 'company_description','company_email',
    'company_phone', 'company_address', 'company_website'
    , 'company_status', 'company_monthly_payment']
    def get_context_data(self, **context):
        context[self.context_object_name] = self.object
        context["extrainfo"] = "Processador123123"
        return context

1 个答案:

答案 0 :(得分:0)

您好,有几种方法可以实现这一目标。

一种方法是像这样过度处理get_context_data:

class CompanyUpdateView(UpdateView):
    model = Company
    context_object_name = 'company'
    template_name = 'company.html'
    fields = [
        'company_name', 'company_description','company_email',
        'company_phone', 'company_address', 'company_website',
        'company_status', 'company_monthly_payment'
    ]

    def get_context_data(self,**kwargs):
        #call the default get_context_data 
        context = super(CompanyUpdateView, self).get_context_data(**kwargs)
        #add new value in the context
        context['extrainfo'] = "Processador123123"
        #return the context (wich contains now the ones defines in fields + the new one defined
        return context

在模板中,您可以访问以下值:

<p>{{company.company_name}}</p>
...
<p>{{extrainfo}}</p>

一个非常好的基于类视图的网站是https://ccbv.co.uk/