LoginSignup
15
16

More than 5 years have passed since last update.

Django admin siteでアクションを追加する

Last updated at Posted at 2013-11-21

django admin siteを利用するには、mysite.appname.admin内で admin siteで管理したいモデルAdminクラス(のサブクラス) を登録する。

Adminクラスのサブクラスをカスタマイズすることで、admin siteでの挙動を変更することが出来る。ここでは特定のアクションを追加する方法を紹介。

## アクションを実行した場合の処理
def update_lnglat(modeladmin, request, queryset):
    """Shopクエリセットを元に、Shopモデルの位置情報を更新する。
    """
    for shop in queryset.all():
        # 位置情報を更新する
        update_shop_lnglat(shop)

# アクションに表示する場合の名前
update_lnglat.short_description = _(u"Update shop location info by address")

## Admin
class ShopAdmin(admin.ModelAdmin):
    list_display = ('name', 'region', 'slug', 'email', 'phone', 'fax', 'lnglat')

    # callableなオブジェクトを渡す
    actions = [update_lnglat]

## admin siteへの登録
admin.site.register(Shop, ShopAdmin)

ShopAdminクラスのactionsプロパティで定義された関数がdjangoの管理画面上に表示される。コード中でshort_descriptionを定義しており、これが表示されていることが解る。

スクリーンショット 2013-11-21 11.33.09.png

関数には次の引数が渡る。

  • ModelAdmin(この場合はShopAdmin)
  • HttpRequest
  • QuerySet

3番目はチェックを付けたオブジェクトが含まれるQuerySetが渡る。これをループで回せば「チェックを付けた対象に対して特定の処理を行う」というのが実現できる。

参考

15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16