Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Can't override admin templates when they are already overridden?

To add some content to a Django admin view of a model, I want to override the change_form.html template. According to the documentation I would need to create a file change_form.html in a the folder /project-path/templates/admin/appname/modelname/. Of course I need to make sure, that this path is also available in TEMPLATE_DIRS. Such a file could look like this:

{% extends "admin/change_form.html" %}
{% load i18n  %}

{% block after_field_sets %}
SOME CONTENT
{% endblock %}

However, I make use of django-guardian to have object permissions. This Django app overrides change_form.html as well (which works fine -- relevant source seems to be here), but Django doesn't pick up my template extension file (i.e. "SOME CONTENT" from the sample above isn't displayed). The blocks/parts I want to override are not the same ones that django-guardian overrides and eventually I want to have the additions to change_form.html of django-guardion and of my template.

What am I doing wrong here? And is possible at all to have multiple applications overriding an admin template?

If it is of interest, this is my TEMPLATE_LOADERS setting:

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader'
)

Also, django-guardian is the last app in the INSTALLED_APPS array.

like image 339
tomka Avatar asked Feb 19 '23 16:02

tomka


1 Answers

One possible solution seems to be to explicitly define the inheritance chain by referring to and overriding django-guardian's template (defined here) and not Django's general change_form.html. So instead of using

{% extends "admin/change_form.html" %}

in the beginning of my custom template, I would need to use

{% extends "admin/guardian/model/change_form.html" %}

Also I would need to extend my GuardedModelAdmin sub-class model to explicitly use my own template file as the change form template:

class MyModel(GuardedModelAdmin):
    change_form_template = 'admin/appname/mymodel/change_form.html'

This works, but it adds a clear dependency to the template and the model. Of course, the model has this dependency anyway, but I would be interested if there is also a solution that refers only to the default change_form.html -- however, I suspect that this is not really possible.

like image 99
tomka Avatar answered May 03 '23 14:05

tomka