开发者

Django modelform: exclude fields by regex

开发者 https://www.devze.com 2022-12-12 13:47 出处:网络
I have a \"Villa\" Model with lots of descriptive TextFi开发者_运维技巧elds. For each TextField, I have a copy which will be the Russian translation of the original field, which I\'m naming by appendi

I have a "Villa" Model with lots of descriptive TextFi开发者_运维技巧elds. For each TextField, I have a copy which will be the Russian translation of the original field, which I'm naming by appending "_ru", for example "long_description" and "long_description_ru". I would like to exclude all the "_ru" fields from my ModelForm, which I thought I would be able to do like this:

class VillaForm(ModelForm):
    class Meta:
        model = Villa
        exclude = []
        for field_name in Villa.__dict__:
            print field_name
            if field_name.endswith("_ru"):
                exclude.append(field_name)

However, Villa.__dict__ does not contain the TextFields - even though they get rendered by the ModelForm. Am I being very stupid here?


I see it's been a while since you asked this but I have an answer for you. I think this might be easier to do in the __init__ function:

class VillaForm(ModelForm):
    class Meta:
        model = Villa

    def __init__(self, *args, **kwargs):
        super(VillaForm, self).__init__(*args, **kwargs)
        for field_name in self.fields.keys():
            if field_name.endswith("_ru"):
                del self.fields[field_name]

The code is not entirely tested but I do think it's easier to do in the __init__ vs. in the Meta definition.

0

精彩评论

暂无评论...
验证码 换一张
取 消