Search code examples
djangodjango-templatesoverriding

django admin template overriding not working


I want to override templates/admin/change_form.html in my own django module app1, so following the standard, i added file change_form.html with following content to app1->templates->admin

{% extends "admin/change_form.html" %}
{% load i18n static %}
{% block object-tools %}
    <h3>My extended html</h3> => Not rendered until => change_form_template = 'admin/change_form1.html'
    {{ block.super }}
    <script defer="defer" src="{% static 'app1/image_preview.js' %}"></script>
{% endblock %}

admin.py (I can achieve it by changing every admin and add giving change_form_template = 'admin/change_form1.html' but that is not the way i need it)

from django.contrib import admin
from .models import Model1
class Model1Admin(admin.ModelAdmin):
    # change_form_template = 'admin/change_form1.html' #overriding does not affect, but this does
    pass
admin.site.register(Model1, Model1Admin)

Expected output: <h3>My extended html</h3> should be the part of every change_form.html because I have extended admin/chamge_form.html without doing anything else anywhere while app1 exists in project and installed app in settings.py


Complete steps (I have Django installed in default python of my system)

  1. django-admin startproject pr1
  2. cd pr1
  3. django-admin startapp app1
  4. edited settings.py to append a line => INSTALLED_APPS += ['app1']
  5. Added chnage_form.html to app1/templates/admin
  6. Made migrations, created superuser, logged in and opened http://127.0.0.1:8000/admin/app2/model1/add/

Complete code https://github.com/humblesami/django-templates

Edit: Chatgpt answer

enter image description here

This does not work either, you check my github code. Also I have tried to add templates/admin in root directory of project, but nothing appears in rendered change_form.html


Solution

  • Add your template to

    app1/templates/admin/change_form.html
    

    as

    {% extends "admin/change_form.html" %}
    {% load i18n static %}
    {% block object-tools %}
        <h2>Preivew</h2>
        {{ block.super }}
        <script defer="defer" src="{% static 'app1/image_preview.js' %}"></script>
    {% endblock %}    
    

    Now the mistake/problem in my code/process was adding app1 to the end of apps list in settings.py which did not work but it must be added before 'django.contrib.admin' so app1/templates/admin/change_form.html will be executed after the original admin/change_form.html, so customization/updates in html will appear.

    INSTALLED_APPS = INSTALLED_APPS + ['app1'] //does not work
    //but
    INSTALLED_APPS = ['app1'] + INSTALLED_APPS //works