来自管理员的 Django 信号 [英] Django signals from admin

查看:14
本文介绍了来自管理员的 Django 信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何区分来自常规视图的 post_save 和来自管理员的 post_save?

How can I distinguish between, for example, a post_save that comes from a regular view and one that comes from the admin?

推荐答案

通过覆盖 ModelAdmin.response_add 您可能会获得类似的功能,因为 django 管理员似乎没有发送任何信号.

By overriding ModelAdmin.response_add you may get a similar functionality, as it seems that the django admin does not sent any signals.

response_add 函数在成功验证并添加所有数据(例如相关字段以及对象本身)后被调用.

The response_add function gets called after it successfully validated and added all data, such as related fields but also the object itself.

因此,通过在我们自己的 ModelAdmin 类中覆盖 response_add 方法,我们可以在 admin 中的某些内容成功添加后执行代码,但不会在其他地方执行.

So by overriding the response_add method in our own ModelAdmin class we can execute code after something in the admin got added successfully, but won't be executed somewhere else.

我在 django 1.4 中做了以下方式,非常感谢任何评论或反馈!就我而言,它似乎运行良好,但我对 Django 中的所有内部结构还不是很熟悉,如果这是一种建议的方法.但对我来说,这听起来比 threadlocal hack 更好.

I did the following way in django 1.4, any comments or feedback greatly appreciated! It seems to be working well in my case, but I'm not so familiar with all the internals in Django yet and if it's a suggested way to do it. But it sounds better than a threadlocal hack to me.

旁注:我想您也可以通过覆盖 ModelAdmin 自己触发信号,但没有经验.

Side note: I guess you could also fire signals yourself by overriding the ModelAdmin, but not experience with that.

这是我用来覆盖response_add的代码,它将执行product_get_initial_info(obj.id)只有一个产品在admin中成功添加:

This is the code I used to override response_add, which will execute product_get_initial_info(obj.id) only a product was successfully added in the admin:

class ProductAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    inlines = [
        ProductInline,
    ]
    def response_add(self, request, obj, post_url_continue='../%s/'):
        if obj and obj.id:
            tasks.product_get_initial_info(obj.id)
        return super(ProductAdmin, self).response_add(request, obj, post_url_continue='../%s/')

相关的django源码在这里:django/contrib/admin/options.py

The related django source code is here: django/contrib/admin/options.py

class ModelAdmin(BaseModelAdmin):
    def add_view(self, request,...)
        # .... Many lines of code ...... not putting them here as they're not so relevant
        if all_valid(formsets) and form_validated:
            self.save_model(request, new_object, form, False)
            self.save_related(request, form, formsets, False)
            self.log_addition(request, new_object)
            # After saving everything response_add gets called with the newly created object
            return self.response_add(request, new_object)

这篇关于来自管理员的 Django 信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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