简体   繁体   English

从Django中的generic.UpdateView访问表单方法

[英]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() . 我有一个视图,它是一个generic.UpdateView ,并且我需要访问一种表单方法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. 我目前使用self.form_class().get_hidden_fields()但是我不确定这是否正确。 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 https://github.com/speedy-net/speedy-net/blob/staging/speedy/match/matches/views.py#L54

I can access the form method directly from the template: 我可以直接从模板访问form方法:

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

link 链接

However, if I need to access the form from Python, I think the correct way is to use cd['form'] in get_context_data (after calling cd = super().get_context_data(**kwargs) ). 但是,如果我需要从Python访问表单,我认为正确的方法是在get_context_data使用cd['form'] (在调用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

Update-1: 10th Aug 更新1:8月10日

def get_context_data(self, **kwargs):
    if "form" in kwargs:
        form = kwargs['form']
    else:
        form = self.get_form()
        kwargs['form'] = form

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

This is another approach that you can use, because when you call get_context_data it will create the form it is not there. 这是可以使用的另一种方法,因为当您调用get_context_data ,它将创建不存在的表单。 This means either you create or let it create the form. 这意味着您可以创建或让其创建表单。 If the get_context_data of the inherited class does it, then it does in kwargs which you can't extract without a hacky way. 如果继承类的get_context_data执行此操作,则它将以kwargs ,如果没有hacky方法,则无法提取。

Original approach 原始方法

So you can use the approach you have where you initiate the class, or you can use a combo approach where the same method can work as a class method as well as a instance method. 因此,您可以在初始化类时使用您拥有的方法,也可以在组合方法中将同一个方法用作类方法和实例方法,然后使用组合方法。 The technique is shown in below article 该技术如下文所示

Creating a method that is simultaneously an instance and class method 创建同时作为实例和类方法的方法

A demo of the same is below 下面是一个相同的演示

import functools


class combomethod(object):
    def __init__(self, method):
        self.method = method

    def __get__(self, obj=None, objtype=None):
        @functools.wraps(self.method)
        def _wrapper(*args, **kwargs):
            if obj is not None:
                return self.method(obj, *args, **kwargs)
            else:
                return self.method(objtype, *args, **kwargs)

        return _wrapper


class SpeedyMatchSettingsMiniForm(object):
    @combomethod
    def get_fields(self):
        return ('gender_to_match', 'match_description', 'min_age_to_match', 'max_age_to_match', 'diet_match', 'smoking_status_match', 'relationship_status_match')

    @combomethod
    def get_visible_fields(self):
        return ('diet_match', 'min_age_to_match', 'max_age_to_match')

    @combomethod
    def get_hidden_fields(self):
        fields = self.get_fields()
        visible_fields = self.get_visible_fields()
        return (field_name for field_name in fields if (not (field_name in visible_fields)))


print(list(SpeedyMatchSettingsMiniForm().get_hidden_fields()))
print(list(SpeedyMatchSettingsMiniForm.get_hidden_fields()))

And the output is 输出是

['gender_to_match', 'match_description', 'smoking_status_match', 'relationship_status_match']
['gender_to_match', 'match_description', 'smoking_status_match', 'relationship_status_match']

So this way in your case you use the Class object directly 因此,在这种情况下,您可以直接使用Class对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM