子类化Django ModelForms [英] Subclassing Django ModelForms

查看:71
本文介绍了子类化Django ModelForms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展ModelForms,其主要目的是向表单添加字段。我想举个例子更容易看到:

I want to extend ModelForms with the main purpose of adding fields to the form. I think it is easier to see with an example:

# Basic listing
class BasicForm(ModelForm):
    class Meta:
        model = Business
        fields = ('category', 'city', 'name', 'address', 
                'slogan', 'phone', 'website', 'email')

class SocialForm(BasicForm):
    class Meta:
        model = Business
        fields = ('facebook','twitter')

那还能行吗?还是只是从SocialForm中的BasicForm中清除掉其他字段?

Would that even work? Or would it just wipe out the other fields from BasicForm in SocialForm?

这样做的正确方法是什么?

What is the correct way of doing this?

推荐答案

这是一个很晚的答案,但我想指出,您可以像这样子化内部 Meta 类:

This is a late answer, but I wanted to note that you can subclass the inner Meta class like this:

class SocialForm(BasicForm):
    class Meta(BasicForm.Meta):
        fields = BasicForm.Meta.fields + ('facebook', 'twitter')

这样,您不必重复 model =业务定义,以及您可以添加到 BasicForm Meta 属性c $ c>将自动被 SocialForm 继承。

That way you don't have to repeat the model = Business definition, and any other Meta attributes you may add to BasicForm will automatically be inherited by SocialForm.

作为参考,这是 Django文档有关此方法。

For reference, here's the Django documentation on this approach.

这篇关于子类化Django ModelForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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