Django forms how to add form field attribute

谁说我不能喝 提交于 2021-01-29 11:31:38

问题


I'm using django-crispy-forms I want to add an attribute http-prefix to the outputted domain field, for example like this...

<input type="text" name="domain" http-prefix>

How is this possible? I can see crispy-forms has the ability to add css to a field self.helper.field_class, but I cannot see where to add an attribute to a field like my example above just http-prefix.

My Form:

class SchemeForm(NgModelFormMixin, forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(SchemeForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8'
        self.helper.layout = Layout(
        'name',
        'domain',
        'slug',


    class Meta:
        model = Scheme
        fields = ('name', 'domain', 'slug')

回答1:


Simply update the attribute by setting the value to empty string:

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

    #...
    self.fields['domain'].widget.attrs['http-prefix'] = ''


来源:https://stackoverflow.com/questions/20999795/django-forms-how-to-add-form-field-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!