gpt4 book ai didi

python - 如何在表单的子类中排除 ModelForm 中声明的字段?

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:07 26 4
gpt4 key购买 nike

在 Django 中,我试图从 ModelForm 表单派生(子类)一个新表单,我想在其中删除一些字段(或者只有一些字段,更正确)。当然,显而易见的方法是(基本形式来自 django.contrib.auth.forms):

class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
fields = ('first_name', 'last_name', 'email')

但这不起作用,因为它还在生成的表单中添加/保留了一个 username 字段。此字段已在 UserChangeForm 中明确声明。即使将 username 添加到 exclude 属性也无济于事。

是否有一些正确的方法来排除它而我遗漏了什么?这是一个错误吗?有什么解决方法吗?

最佳答案

试试这个:

class MyUserChangeForm(UserChangeForm):

def __init__(self, *args, **kwargs):
super(MyUserChangeForm, self).__init__(*args, **kwargs)
self.fields.pop('username')

class Meta(UserChangeForm.Meta):
fields = ('first_name', 'last_name', 'email')

这会在创建表单时动态地从表单中删除一个字段。

关于python - 如何在表单的子类中排除 ModelForm 中声明的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3287974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com