2011-06-03 9 views
3

インラインが添付されているものに応じて、汎用インラインで見つかるFKフィールドの選択を制限しようとしています。インラインが関連しているオブジェクトに依存する汎用インラインFKフィールドへの選択の制限

たとえば、Articleと編集された一般的な関係Publishingを持つArticleがあります。

私はPublishingInlineが現在、アーティクルにインラインで編集中であることを「知って」いるようにしたいと考えています。利用可能なPublishingTypesをcontent_typeArticleに制限しています。

class PublishingInlineForm(forms.ModelForm): 

    def __init__(self, *args, **kwargs): 

     try: 
      data = kwargs.pop("data", {}) 
      if kwargs["instance"]: 
       publishing_type_kwargs = { 
        'content_type': kwargs["instance"].content_type, } 
       data["publishing_type"] = PublishingType.objects.filter(**publishing_type_kwargs) 
       kwargs["data"] = data 
     except KeyError: 
      pass 

     super(PublishingInlineForm, self).__init__(*args, **kwargs) 

class PublishingInline(generic.GenericStackedInline): 

    form = PublishingInlineForm 

    model = get_model('publishing', 'publishing') 
    extra = 0 

答えて

2

私が正しくあなたを理解していれば、あなたのGenericInlineModelAdminformfield_for_foreignkeyはあなたの友達です:

これは私が作ったスタートです。

これらの線に沿って何かがそれを実行する必要があります。

def formfield_for_foreignkey(self, db_field, request, **kwargs): 
    print self.parent_model # should give you the model the inline is attached to 
    if db_field.name == "publishing_type": 
     kwargs["queryset"] = ... # here you can filter the selectable publishing types based on your parent model 
    return super(PublishingInline, self).formfield_for_foreignkey(db_field, request, **kwargs) 
+0

Supurb!あなたが正しいことを見つけると、それはとても簡単です:) – Daryl

関連する問題