在Django Admin中向每个视图(base_site.html)添加内容 [英] Adding content to each view(base_site.html) in Django Admin

查看:74
本文介绍了在Django Admin中向每个视图(base_site.html)添加内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Djando管理员 delete_view change_view 中将对象列表传递给我的自定义模板.我修改了base_site.html,使其包含导航栏,并且我想从视图中将对象列表传递给导航栏.

I want to pass a list of object to my custom template in Djando admin, delete_view and change_view. I modified base_site.html for including a nav-bar and I want to pass, from view, a list of objects to the nav-bar.

我之前为django管理员索引,changelist_view和add_view做过.我重写了这些功能,并添加了我想要的额外内容.

I did it before for django admin index, changelist_view and add_view as well. I override those function and add the extra content I want.

但是我不能两次做到.这个想法应该是这样的:

But I can´t do it in the two firts. The idea should be this one:

@csrf_protect_m
@transaction.atomic
def delete_view(self, request, object_id, extra_context=None):
    extra_context = extra_context or {}                 
    mygetModels = getModels()
    extra_context["modelsTables"] = mygetModels.getTablesModels()
    return super(table_NameAdmin, self).delete_view(request, object_id, extra_context)

正如我之前说过的那样,它可以在changelist_view,index和add_view中使用.但是不能在 delete_view change_view 中使用.

As I said that works before in changelist_view, index and add_view. But is not working in delete_view and change_view.

推荐答案

从您发布的代码中,我不确定为什么您的 delete_view 无法正常工作.我建议使用另一种方法向上下文中添加项目.

From the code you have posted, I'm not sure why your delete_view isn't working. I suggest a different approach to add items to the context.

尝试覆盖管理网站的 each_context 方法.这样避免了必须重写多个模型管理方法.

Try overriding your admin site's each_context method. This avoids having to override multiple model admin methods.

def each_context(self, request):
    context = super(MyAdminSite, self).each_context(request)
    context['extra_var'] = 'Extra variable'
    return context

如果您想在Django管理员之外的模板中使用这些变量,则可以编写上下文处理器.

If you wanted to use these variables in templates outside of the Django admin, you could write a custom template tag or context processor.

如果您使用的是Django 1.9+,则可以使用 simple_tag 装饰器将标记的结果保存到变量中.

If you are using Django 1.9+, you can use the simple_tag decorator to save the result of the tag to a variable.

{% getTablesModels as modelsTables %}

然后您可以在模板中使用变量

Then you can use the variable in the template

{% for item in modelsTables %}

这篇关于在Django Admin中向每个视图(base_site.html)添加内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆