【问题标题】:django: Required Field Not Having The "required" Attribute in HTMLdjango:必填字段在 HTML 中没有“必需”属性
【发布时间】:2016-05-05 07:36:51
【问题描述】:

我是 django 的新手,我认为到目前为止它很棒。我今天遇到了这个奇怪的问题: 我有这个 FormModel:

class RegisterForm2(UserCreationForm):
    mobile2 = forms.CharField(
        label=_('Mobile Confirmation'),
        max_length=50,
        required=True,
        widget = forms.TextInput(attrs = {'class':'nocopy'})
    )

    class Meta:
        model = User
        fields = ['username', 'mobile', 'mobile2', 'guardian_mobile']
        labels = {
            'username': _('Government ID'),
        }
        widgets = {
            # workaround since __init__ setting to required doesnt work
            'mobile': forms.TextInput(attrs = {'required':''}),
        }

    def __init__(self, *args, **kwargs):
        super(RegisterForm2, self).__init__(*args, **kwargs)

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

现在移动字段在模型中有 blank=True 但我希望它只在表单中是必需的,所以我在 __init__ 中做到了。现在它使该字段成为必填字段,但并未将 required="" 添加到文本输入中。现在,如果我像 mobile2 字段那样覆盖了该字段(并添加了 required=True),我就不会有这个问题了。这是一个问题,因为如果我希望在字段上显示所需的属性,我必须覆盖表单中的字段以添加 required=True 这将违反 DRY 原则。我错过了什么还是这是某种错误?

编辑: 我没有提到我正在使用软盘表格。可能与此有关。我必须进一步调查这个问题。

【问题讨论】:

  • 这正是blank 的用途
  • @Sayse 我想将模型字段保留为空白=True,但在模型表单中强制要求=True,而不覆盖整个字段的定义。我可以从 init 中做到这一点,但该字段显示没有“必需的”HTML 属性。
  • 哦,所以您正在寻找客户端验证而不是服务器端? Alasdails 的回答涵盖了这一点

标签: python django django-models django-forms django-floppyforms


【解决方案1】:

这实际上在您的__init__ 中是可能的。您只需将所需的属性添加到小部件属性:

def __init__(self, *args, **kwargs): super(RegisterForm2, self).__init__(*args, **kwargs) self.fields['mobile'].required = True self.fields['mobile'].widget.attrs['required'] = 'required'

【讨论】:

    【解决方案2】:

    请注意,此答案假定您使用的是常规 Django 表单,我在您提到您使用的是软盘表单之前写了它。

    Django 当前在呈现表单字段时不添加required HTML 5 属性。在我看来,覆盖 mobile 字段的小部件听起来不错。您正在更改小部件,而不是复制字段,所以我认为您不必担心它会干燥。

    请注意,__init__ 中所需的设置会产生影响 - 如果您提交的表单中 mobile 的值为空,那么您将收到验证错误。 mobile2 字段在呈现的 HTML 中不会有 required,除非您将其添加到其小部件属性中。

    Django 将在 Django 1.10 中将required 属性添加到表单字段,请参阅ticket #22383

    【讨论】:

    • 我正在使用 django 1.95,并在其中为 mobile2 添加了 HTML 中的必需属性,尽管我没有在小部件属性中添加它。仅当您在表单中重新定义字段(不是 DRY)并指定 required=True 时,django 才会添加 required 属性。
    • 它在 HTML 中为 mobile2 添加了 required 属性——这不是我在 Django 1.9 中看到的行为,或者通过查看代码/票证来预期。也许您正在以一些您没有告诉我们的自定义方式呈现字段(例如使用清晰的表单)。
    • 会不会和软盘表格有关?我没有提到这一点
    • 如果您使用软盘形式,您会看到不同的行为。 It does include the required attribute.
    【解决方案3】:

    但我希望它只需要在表单中

    'mobile': forms.TextInput(attrs = {'required':''}),
    

    您也可以在 views.py 中执行此操作。这就是我喜欢的方式。

    form.fields['mobile'].widget.attrs['required'] = True 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 2017-10-24
      • 2017-03-30
      • 2013-04-18
      相关资源
      最近更新 更多