Django: How do I add arbitrary html attributes to input fields on a form?

若如初见. 提交于 2019-11-26 21:38:08

Check this page

city = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))

Sorry for advertisment, but I've recently released an app (https://github.com/kmike/django-widget-tweaks) that makes such tasks even less painful so designers can do that without touching python code:

{% load widget_tweaks %}
...
<div class="field">
   {{ form.city|attr:"autocomplete:off"|add_class:"my_css_class" }}
</div>

or, alternatively,

{% load widget_tweaks %}
...
<div class="field">
   {% render_field form.city autocomplete="off" class+="my_css_class" %}
</div>
Artificioo

If you are using "ModelForm":

class YourModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['city'].widget.attrs.update({
            'autocomplete': 'off'
        })
Wtower

If you are using ModelForm, apart from the possibility of using __init__ as @Artificioo provided in his answer, there is a widgets dictionary in Meta for that matter:

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        widgets = {
            'name': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

Relevant documentation

I did't want to use an entire app for this thing. Instead I found the following code here https://blog.joeymasip.com/how-to-add-attributes-to-form-widgets-in-django-templates/

# utils.py
from django.template import Library
register = Library()

@register.filter(name='add_attr')
def add_attr(field, css):
    attrs = {}
    definition = css.split(',')

    for d in definition:
        if ':' not in d:
            attrs['class'] = d
        else:
            key, val = d.split(':')
            attrs[key] = val

    return field.as_widget(attrs=attrs)

use the tag in the html file

{% load utils %}
{{ form.field_1|add_attr:"class:my_class1 my_class2" }}
{{ form.field_2|add_attr:"class:my_class1 my_class2,autocomplete:off" }}

I have faced the same issue and was able to solve it as follows: I followed the code in this link and added a little modification https://blog.joeymasip.com/how-to-add-attributes-to-form-widgets-in-django-templates/

Summery :

Step 1: create a file called add_attr.py and place it in templatetags folder inside your application

Step 2: add the following code to add_attr.py

from django.template import Library
register = Library()

@register.filter(name='add_attr')
def add_attr(field, css):
    attrs = {}
    definition = css.split(',')

    for d in definition:
        if '=' not in d:
            attrs['class'] = d
        else:
            key, val = d.split('=')
            attrs[key] = val
    return field.as_widget(attrs=attrs)

Step 3: Using the tag as follows : load the tag:

{% load add_attr %}

example:

<input type="email" id="defaultLoginFormEmail" class="form-control mb-4" placeholder="E-mail">

becomes

{{ form.email|add_attr:'id=defaultLoginFormEmail,class=form-control mb-4,placeholder=E-mail' }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!