Django Crispy Forms add HTML Attributes

1.2k Views Asked by At

My goal is to have LastPass ignore all input forms on my site. I am using crispy forms and showing all form fields with only this in my HTML:

{{ form|crispy }}

However, I want to edit some of the HTML attributes of all input elements created by this form WITHOUT writing each one individually. LastPass recommends that I use data-lpignore="true" in my HTML input tags. I tried to implement that in my form tags, but that didn't work (yes, I know, form != input). :

<form action="{{ action }}" method="post" class="no-ajax" data-lpignore="true">
  {% csrf_token %}
  {{ form|crispy }}
  <input type="submit" name="submit" value="Save" class="btn btn-primary btn-lg" />
</form>

This didn't work.

I also tried including the following in SETTINGS.py:

CRISPY_CLASS_CONVERTERS = {'data-lpignore': 'true'}

Which is supposed to add data-lpignore="true" to my crispy form input tags according to crispy forms' documentation, but this didn't work.

Am I stuck doing individual input lines or is there a better solution?

1

There are 1 best solutions below

0
On

In your form class, pass default attributes to the widget used to render your form fields. For example,

from django import forms

DEFAULT_ATTRS = {'data-lpignore': 'true'}
...
class SampleForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs=DEFAULT_ATTRS))