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

查看:59
本文介绍了管理员的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的所有内部组件还不太熟悉,如果这是一种建议的实现方式,我也不太熟悉.但对我来说,这听起来比线程本地黑客更好.

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):

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天全站免登陆