首页 > 解决方案 > Access a form method from generic.UpdateView in Django

问题描述

I have a view which is a generic.UpdateView, and I need to access a form method - get_hidden_fields(). How do I access it?

I currently used self.form_class().get_hidden_fields() but I'm not sure if this is correct. I think it creates a new instance of the form and I want to use the current instance.

def get_context_data(self, **kwargs):
    cd = super().get_context_data(**kwargs)
    cd.update({
        'matches_list': self.page.object_list,
        'form_hidden_fields': list(self.form_class().get_hidden_fields()),
    })
    return cd

https://github.com/speedy-net/speedy-net/blob/staging/speedy/match/matches/views.py#L54

标签: pythondjangodjango-formsdjango-views

解决方案


我可以直接从模板访问表单方法:

{% if field.name in form.get_hidden_fields %}

关联

但是,如果我需要从 Python 访问表单,我认为正确的方法是使用cd['form']in get_context_data(在调用之后cd = super().get_context_data(**kwargs))。

def get_context_data(self, **kwargs):
    cd = super().get_context_data(**kwargs)
    cd.update({
        'matches_list': self.page.object_list,
        'form_hidden_fields': list(cd['form'].get_hidden_fields()),
    })
    return cd

推荐阅读