この関数をシグナルハンドラとして試してください:
def location_title(sender, instance, created, **kwargs):
# Don't fire up on updates.
if not created:
return
# Only handle new superusers.
if not instance.is_superuser or not instance.is_active:
return
# Create a `Location` entry for new superuser.
l = Location(user_id=instance.pk)
l.save()
post_save.connect(location_title, sender=User)
モデル フィールドへの選択肢の追加:
Django CharField には名前付き引数choices
があり、エンドユーザーに可能な値のリストを提供し、フォームでそれらを適切に検証できます。iterable の形式は次のとおり<internal_value>, <display_value>
です。フィールドにchoices
引数が渡されると、メソッドを使用して内部値に接続された表示値にアクセスできますinstance.get_<field_name>_display()
。
反復可能な選択肢は次のようになります。
class Location(models.Model):
class Title:
CLASSROOM = 'classroom'
PLAYGROUND = 'playground'
STAFF_ROOM = 'staff_room'
TITLE_CHOICES = (
(Title.CLASSROOM, 'Classroom'),
(Title.PLAYGROUND, 'Playground'),
(Title.STAFF_ROOM, 'Staff Room'),
)
user = models.ForeignKey(User,null=True)
title = models.CharField('Incident Type', max_length=200,choices=TITLE_CHOICES,default=Title.CLASSROOM)
parent_location_id = models.CharField('Parent Location', max_length=100, null=True, blank=True)
is_active = models.BooleanField('Is Active', default=True)
最終的な解決策は次のとおりです。
class Location(models.Model):
class Title:
CLASSROOM = 'classroom'
PLAYGROUND = 'playground'
STAFF_ROOM = 'staff_room'
BASE_LOCATION = Title.CLASSROOM
TITLE_CHOICES = (
(Title.CLASSROOM, 'Classroom'),
(Title.PLAYGROUND, 'Playground'),
(Title.STAFF_ROOM, 'Staff Room'),
)
user = models.ForeignKey(User,null=True)
title = models.CharField('Incident Type', max_length=200,choices=TITLE_CHOICES,default=Title.CLASSROOM)
parent_location_id = models.CharField('Parent Location', max_length=100, null=True, blank=True)
is_active = models.BooleanField('Is Active', default=True)
def location_title(sender, instance, created, **kwargs):
# Don't fire up on updates.
if not created:
return
# Only handle new superusers.
if not instance.is_superuser or not instance.is_active:
return
# Create a `Location` entry for new superuser.
base = Location(user_id=instance.pk, title=Location.BASE_LOCATION)
base.save()
for value, _ in Location.TITLE_CHOICES:
if value == Location.BASE_LOCATION:
continue
l = Location(user_id=instance.pk, title=value, parent_location_id=base.pk)
l.save()
post_save.connect(location_title, sender=User)