简体   繁体   English

Django管理员外键值自定义表单

[英]Django admin foreign key values custom form

So, I have a model Puzzle and a model Piece. 因此,我有一个拼图模型和一个样片。 Piece has as foreignKey to Puzzle. 片具有作为拼图的外键。 And on the admin, on puzzle form to add a new element, i have a stackedInLine for pieces. 在管理员上,在拼图上添加新元素的表单上,我有一个stackedInLine。 But i can only add more if I enter all the data from the piece. 但是,只有输入所有数据,我才能添加更多内容。 Is there a way to add new Pieces to the puzzle by choosing from a dropdown with the Piece values already stored on the DB ?? 有没有一种方法可以通过从下拉列表中选择已经存储在数据库中的计件值来添加新的计件? I google'd forever and found nothing....thanks. 我永远用Google搜索,什么也没找到。 So what I have is: 所以我有:

class Puzzle(models.Model):
     name = models.CharField(max_length=200)

class Piece(models.Model):
     name = models.CharField(max_length=200)
     puzzle = models.ForeignKey(Puzzle, null=True)

And on the django backend, when I am editing a puzzle I would like to choose from a dropdown of all the Piece models stored on the DB and "assign" them to the current puzzle i'm editing. 在django后端上,当我编辑拼图时,我想从存储在数据库中的所有Piece模型的下拉列表中进行选择,然后将它们“分配”到我正在编辑的当前拼图中。 Is this possible? 这可能吗? I'm at the moment using: 我目前正在使用:

class PieceInline(admin.StackedInline):
      model = Piece
      extra = 1
class PuzzleAdmin(admin.ModelAdmin):
      model = Piece
      inlines = (PieceInLine, )

So I have a stackedinline of pieces on the puzzle form, but I can only create new ones... 所以我在拼图形式上有很多堆叠的内容,但是我只能创建新的内容...

What if you create a new model, say: 如果创建一个新模型,请说:

from django.dispatch import receiver


class PieceSelector(models.Model):
    piece = models.ForeignKey(Piece)

    def __unicode__(self):
        return piece.some_field

@receiver(post_save, sender=Piece)
def piece_post_save_signal_receiver(sender, **kwargs):
    if kwargs['created']:
        PieceSelector.objects.create(piece=kwargs['instance'])

Now, when you create a Piece model object, you should create PieceSelector object too. 现在,当您创建Piece模型对象时,您也应该创建PieceSelector对象。 You can do it using post_save signal of the Piece model and it will provide all the pieces in a dropdown. 您可以使用Piece模型的post_save信号进行操作,它将在下拉菜单中提供所有片段。

When in the admin.py, use PieceSelector as a StackedInline for Puzzle model. 在admin.py中时,将PieceSelector用作Puzzle模型的StackedInline。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM