Django:重用表单域而不继承? [英] Django: Reuse form fields without inheriting?

查看:79
本文介绍了Django:重用表单域而不继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两种基于不同的基类(比如Form和ModelForm)的形式,但是我想在两者中使用几个字段,我可以用DRY方式重用它们吗?

If I have two forms, based on different base classes (say, Form and ModelForm), but I want to use a few fields in both, can I reuse them in a DRY way?

考虑以下情况:

class AfricanSwallowForm(forms.ModelForm):
    airspeed_velocity = forms.IntegerField(some_important_details_here)
    is_migratory = forms.BooleanField(more_important_details)

    class Meta:
        model = AfricanBird

class EuropeanSwallowForm(forms.Form):
    airspeed_velocity = forms.IntegerField(some_important_details_here)
    is_migratory = forms.BooleanField(more_important_details)

....有没有办法我可以重新使用字段airspeed_velocity和is_migratory?想象一下,我有几十种这样的形式。如果我一再写这个代码,代码将被浸泡。

....is there a way I can just reuse the fields airspeed_velocity and is_migratory? Imagine I have a couple dozen of these type of forms. The code will be soaking if I write these over and over again.

(假设为了这个问题的目的,我不能或不会将空速_速度

(Assume, for the purposes of this question, that I can't or won't turn airspeed_velocity and is_migratory into fields of the model AfricanBird.)

推荐答案

工厂风格的方法如何?

def form_factory(class_name, base, field_dict):
    always_has = {
        'airspeed_velocity': forms.IntegerField(some_important_details_here),
        'is_migratory': forms.BooleanField(more_important_details)
    }
    always_has.update(field_dict)
    return type(class_name, (base,), always_has)

def meta_factory(form_model):
    class Meta:
        model = form_model
    return Meta

AfricanSwallowForm = form_factory('AfricanSwallowForm', forms.ModelForm, {
        'other' = forms.IntegerField(some_important_details_here),
        'Meta': meta_factory(AfricanBird),
    })

EuropeanSwallowForm = form_factory('EuropeanSwallowForm', forms.Form, {
        'and_a_different' = forms.IntegerField(some_important_details_here),
    })

为此,您可以修改工厂函数,查看现有的表单类并选择你想要的属性,这样你就不会失去声明性的语法...

For that matter, you could modify the factory function here to look into an existing form class and pick out the attributes you want, so that you don't lose the declarative syntax...

这篇关于Django:重用表单域而不继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆