1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Djangoの管理サイトでオブジェクトを追加する際に保存前処理を追加する方法

Last updated at Posted at 2020-04-13

開発環境

  • Python 3.7.3
  • Django 3.0.5

※Class-Basedで開発していきます。

models.py

models.py
from django.db import models


class Word(models.Model):
    """単語モデル"""

    word = models.CharField(max_length=15, unique=True)
    # 文字数フィールド
    word_count = models.PositiveSmallIntegerField(blank=True, null=True)

    def __str__(self):
        return self.word

admin.py

admin.py
from django.contrib import admin

from .models import Word


class WordAdmin(admin.ModelAdmin):

    # save_model関数をオーバーライド
    def save_model(self, request, obj, form, change):
        word = obj.word  # wordフィールドの入力値

        # word_count
        word_count = len(word)

        obj.word_count = word_count
        obj.save()  # オブジェクトを保存


# モデルとsave_model関数を指定
admin.site.register(Word, WordAdmin)

完成!

これで、管理サイトでオブジェクトを追加・更新する際に、指定した事前処理が実行されます。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?