Y
Y
Yuri2020-04-18 13:34:33
Django
Yuri, 2020-04-18 13:34:33

Django how to pass variable to template in admin?

How to pass gallery_add to template?

admin.py

class Service_Admin(admin.ModelAdmin):
    save_as=True
    change_form_template = "admin_template.html"
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM some_table ")
        gallery_add = cursor.fetchall()


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

{% block inline_field_sets %}

    {% for inline_admin_formset in inline_admin_formsets %}
        {% include inline_admin_formset.opts.template %}
        {% ifequal inline_admin_formset.formset.prefix 'block_name' %}
            <select id='add_id'>
                <b>{% for line in gallery_add %}
                    <option value='{{ line.id }}'>{{ line.name }}</option>
                {% endfor %}</b>
            </select>
        {% endifequal%}
    {% endfor %}
{% endblock %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2020-04-18
@yuretzgt

The issue is resolved through the definition of change_view and the indication of extra_context there

class Service_Admin(admin.ModelAdmin):
    change_form_template = "admin_template.html"
    def change_view(self, request, object_id, form_url='', extra_context=None):
       extra_context = extra_context or {}
       extra_context['gallery_add'] = "Нужное значение"
       return super(Service_Admin, self).add_view(request, form_url, extra_context)

There is no need to change anything in the template.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question