3

In HTML, the best practice is to use hyphens instead of underscores in names of ids.For example, this post refers to this issue.

However, Django for some reason uses underscores when automatically generating ids from the names of the model fields. Is it possible to override this behaviour somehow ?

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

2 Answers2

2

I don't think you can do anything but overriding the id_for_label() method on a per-widget bases:

def id_for_label(self, id_):
    return id_.replace('_', '-')

But if using hyphens might be better practice in HTML, doing so much work just to have hyphens instead of underscores seems overkill and counter-productive.

Another solution would be to monkey patch django but it seems overkill to me as well.

Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
0

There's lots of reasons you would want to modify the HTML id. Underscores are ugly when mixed with hyphens!

Use auto_id.

By default, auto_id is set to the string 'id_%s'.

You could define this when initializing the form:

form = MyForm(auto_id='id-%s')

or change it in the initialization of your form class:

class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        kwargs.update({'auto_id': 'id-%s'})
        super().__init__(*args, **kwargs)

Modifying id_for_label(self, id_) in a custom widget too:

# widgets.py

class MyTextInput(widgets.TextInput):
    class Media:
        css = {'all': ('myapp/widgets/css/mycustominput.css',)}
        js = ('myapp/widgets/js/mycustominput.js',)

    def id_for_label(self, id_):
        return id_.replace('_', '-')

# forms.py

from .widgets import MyTextInput

class MyForm(forms.ModelForm):

    widgets = {
        'text': MyTextInput(attrs={'class': 'form-control'})
    }
Jarad
  • 17,409
  • 19
  • 95
  • 154