我想将一些自定义数据传递给django admin中的模板。如何在下面的示例中访问myData
?
class MyAdmin(admin.ModelAdmin):
def get_object(self, request, object_id, form_field=None):
obj = super().get_object(request, object_id, form_field)
self.myData = MyModel.objects.filer(id=obj.myData_ID)
return obj
在模板中:
{% for p in myData %}
<p>{{p}}</p>
{% endfor %}
答案 0 :(得分:1)
我认为您可以这样做。我没尝试过
class MyAdmin(admin.ModelAdmin):
def get_object(self, request, object_id, form_field=None):
obj = super().get_object(request, object_id, form_field)
return obj
def render_change_form(self, request, context, *args, **kwargs):
context['myData'] = MyModel.objects.filer(id=obj.myData_ID)
return super(MyAdmin, self).render_change_form(request, context, args, kwargs)
答案 1 :(得分:1)
引用StackOverflow:customizing django admin ChangeForm template / adding custom content
您可以尝试以下方法:
class MyObjectAdmin(admin.ModelAdmin):
# A template for a very customized change view:
change_form_template = 'admin/my_change_form.html'
def get_dynamic_info(self):
# ...
pass
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
extra_context['osm_data'] = self.get_dynamic_info()
return super(MyObjectAdmin, self).change_view(
request, object_id, form_url, extra_context=extra_context,
)