Django:覆盖 ModelAdminForm 的字段属性

发布于 2024-12-03 13:03:23 字数 386 浏览 0 评论 0原文

我试图覆盖 ModelAdmin 的表单字段,如下所示:

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, *args, **kwargs):
        form = super(MyModelAdmin, self).get_form(*args, **kwargs)
        form.fields['password'].help_text = "..."
        return form

我收到属性错误:“类型对象‘FailedLoginForm’没有属性‘字段’”。

ModelAdmin.get_form() 不是返回常规 Django 表单对象吗?怎么没有字段呢?

I am trying to override a ModelAdmin's form field as below:

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, *args, **kwargs):
        form = super(MyModelAdmin, self).get_form(*args, **kwargs)
        form.fields['password'].help_text = "..."
        return form

I am getting an Attribute error: "type object 'FailedLoginForm' has no attribute 'fields'".

Isn't ModelAdmin.get_form() returning a regular Django form object. How come it doesn't have fields?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦幻的心爱 2024-12-10 13:03:23

我建议您只需覆盖您想要的表单即可。

class UserCreationForm(UserCreationForm):   
    # we want to use the email as the username
    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        # let's require these fields
        self.fields['email'].required = True
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True
        # let's not require these
        self.fields['username'].required = False
        self.fields['password1'].required = False
        self.fields['password2'].required = False

从那里你几乎可以做任何你想做的事情。

I suggest that you simply override the form that you want.

class UserCreationForm(UserCreationForm):   
    # we want to use the email as the username
    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        # let's require these fields
        self.fields['email'].required = True
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True
        # let's not require these
        self.fields['username'].required = False
        self.fields['password1'].required = False
        self.fields['password2'].required = False

From there you can do pretty much anything you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文