Django - change form prefix separator

I'm using form prefix to render the same django form twice in the same template and avoid identical fields id's.

When you do so, the separator between the prefix and the field name is '-', I would like it to be '_' instead.

Is it possible ?

Thanks

You could "monkey patch[wiki] the BaseForm code, for example in some AppConfig:

# app_name/config.py

from django.apps import AppConfig


class MyAppConfig(AppConfig):
    def ready(self):
        from django.forms.forms import BaseForm

        def add_prefix(self, field_name):
            return f'{self.prefix}_{field_name}' if self.prefix else field_name

        BaseForm.add_prefix = add_prefix

But I would advise not to do this. This will normally generate the correct prefixes with an underscore. But some Django apps or some logic in the Django project itself might not use this method, and make the assumption it works with an hyphen instead. While probably most of such packages could indeed get fixed, it would take a lot of work.

Back to Top