I am trying to customise a template in the admin panel for a specific model. I managed to override the template and can now change some html elements in the admin template.
What I want to do is to render a summary table within the change template, ideally calling {{summuary_table}}
.somewhere in change_form
template
I am struggling is to call a function/method in the new template.
I followed a few examples and settled on using the code below work. (DJANGO ADMIN Add_view, save_model, and change_view override example django admin · GitHub) I have been trying to stay away from CBV as much as possible as it seems a bit hard for my programming level but it looks like i don’t have a choice here.
I tried to make a basic instance work before starting something a bit more complicated, but even this is not working. Something else I am not clear about is that in this example (see admin.py) all responses I found on internet are referring to object_id
instead of the mymodel_id.
Would be grateful for some pointers.
templates/admin/appname/model/change_form.html
{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}
{% block object-tools-items %}
<li>
<a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a>
</li>
<li>
{{summuary_table}}
</li>
{% if has_absolute_url %}
<li>
<a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a>
</li>
{% endif %}
{% endblock %}
models.py
class MyModel(models.Model):
name = models.ForeignKey(OtherModel1,null=True, blank=True, on_delete=models.SET_NULL)
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
status = models.BooleanField(default=False)
admin.py
class MyModelAdmin(admin.ModelAdmin):
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
summuary_table = MyModel.objects.filter(id=object_id)
extra_context["form"] = self.get_form(instance=summuary_table, request=request)
return super(MyModelAdmin, self).change_view(request, object_id, form_url=form_url, extra_context=extra_context)