Search code examples
djangodjango-templatesdjango-widget

Override Django widgets default templates


I want to override the Django (2.01) widget templates, because I need to add classes for each input, label, and position them differently

app
 - templates
 - app 
    - django
       - forms
           - widgets
             - input.html

enter image description here or

app
 - templates
   - django
      - forms
          - widgets
             - input.html

or template project directory:

- templates
   - django
      - forms
          - widgets
             - input.html

None of them works, (even if I this is how is recommended in docs, and from an answer that I saw on stackoverflow), it still loads from default.

Being general widgets templates, I'm preferring to put them in the template project directory, but from what I reed by default for widgets search only in installed apps.


Solution

  • It looks like this was a problem in Django 1.11.

    Django widget template override does not search in the project template directory. How to fix?

    This is somewhat annoying. It is fixed by changing your settings. So your main site has to have these settings.

    INSTALLED_APPS = [
        ...
        'django.forms',
        ...
    ]
    
    FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
    

    Unfortunately, you cannot automate this by one of your installed apps. If an installed app overrides django template widgets it needs to be documented and users have to add this code in their site settings.

    You don't need to change anything in the "TEMPLATES" setting. Here is what my TEMPLATES looks like for reference.

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]