在Django管理员中,我可以要求模型中的字段,而不是内联的字段? [英] In Django admin, can I require fields in a model but not when it is inline?

查看:101
本文介绍了在Django管理员中,我可以要求模型中的字段,而不是内联的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django管理员中,如果模型被单独编辑,我想要的字段。如果是内联的,我不希望他们被要求。有没有办法这样做?

In django admin, there are fields I'd like to require if a model is being edited standalone. If it is inline, I don't want them to be required. Is there a way to do this?

推荐答案

虽然Daniel Roseman的回答有效,但这不是最好的解决方案。它需要一些代码重复,因为必须重新声明表单字段。例如,如果您在该字段上有 verbose_name ,则还必须添加 label ='我的verbose_name已在模型上设置' CharField 行,因为重新声明整个字段基本上会擦除模型中为该字段设置的所有内容。

While Daniel Roseman's answer works, it's not the best solution. It requires a bit of code duplication by having to re-declare the form field. For example, if you had a verbose_name on that field, you would also have to add label='My verbose_name already set on model' to the CharField line, since re-declaring the whole field basically erases everything set on your model for that field.

更好的方法是覆盖窗体的 __ init __ 方法,并将 field.required 显式设置为 True False 那里。

The better approach is to override the form's __init__ method and explicitly set field.required to True or False there.

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)

        self.fields['myfield'].required = True

这篇关于在Django管理员中,我可以要求模型中的字段,而不是内联的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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