如何在Django表单域中添加必需属性

icnyk63a  于 2023-01-31  发布在  Go
关注(0)|答案(4)|浏览(136)

我想有一个Django表单域渲染为:

<input type="text" name="username" required>

但是当我尝试username.widget.attrs['required'] = ''时,我得到了类似这样的结果:

<input type="text" name="username" required="">

是否有一种方法可以在生成的HTML表单中显示独立的HTML5属性(如required)?
我在Python 2.6上使用Django 1.6,这是值得的。

xiozqbni

xiozqbni1#

@mariodev是正确的,如果你想要一个更优雅的方法,参考https://stackoverflow.com/a/37738828/2812260(相关部分复制如下):
如果你真的想编写优雅的DRY代码,你应该创建一个基类,它可以动态地查找所有的必填字段,并修改它们的widget required属性(你可以随意命名它,但是“BaseForm”似乎很合适):

from django.forms import ModelForm

class BaseForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(BaseForm, self).__init__(*args, **kwargs)
        for bound_field in self:
            if hasattr(bound_field, "field") and bound_field.field.required:
                bound_field.field.widget.attrs["required"] = "required"

然后让所有Form对象从它派生:

class UserForm(BaseForm):
    class Meta:
        model = User
        fields = []

    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    email = forms.EmailField(required=True, max_length=100)
kx1ctssn

kx1ctssn2#

您需要以有效格式定义required属性。

username.widget.attrs['required'] = 'required'

查看此处了解更多详情:https://stackoverflow.com/a/3012975/1566605

6rqinv9w

6rqinv9w3#

如果你想要一个声明性的选项在每一个表单而不是每一个模型的基础上,这是我的解决方案:

from django import forms

class RequiredFieldsModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(RequiredFieldsModelForm, self).__init__(*args, **kwargs)
        for bound_field in self:
            if (
                hasattr(bound_field, "field") and
                bound_field.name in self.Meta.required_fields
            ):
                bound_field.field.widget.attrs["required"] = "required"

# Your forms
class UserForm(RequiredFieldsModelForm):
    class Meta:
        required_fields = ['username']
        model = User
vxbzzdmp

vxbzzdmp4#

只需像这样为widget设置required属性:
self.字段['字段名称'].widget =表单.文本输入(属性={'必需':'必需'})

相关问题