开发者

Custom form in inline form

开发者 https://www.devze.com 2022-12-08 15:25 出处:网络
I have a custom form to display goals. Goals are edited inline in a Game. class GoalForm(forms.ModelForm):

I have a custom form to display goals. Goals are edited inline in a Game.

class GoalForm(forms.ModelForm):

   class Meta:
       model = Goal

   def __init__(self, *args, **kwargs):
       super(GoalForm, self).__init__(*args, **kwargs)
       self.fields['goal_scorer'].queryset =
Player.objects.filter(gameroster__game=self.instance.game)

class GoalInline(admin.TabularInline):
   model = Goal
   extra = 4
   #form = GoalForm


class GameAdmin(admin.ModelAdmin):
   list_display = ('date_time', 'home_team', 'opponent_team',
'is_home_game', 'result')
   list_filter = ['league', 'season']
   inlines = [GameRosterInline, GoalInline, PenaltyInline]
   ordering       = ('date_time',)

开发者_StackOverflowMy custom form is working as long as I edit it "standalone". As soon as I edit it inline, the custom form is going to be ignored. Commenting in the parameter form of the class GoalInline causes Django to crash.

Any idea how to use the custom form inline?


I don't think admin always passes instance keyword when instantiating inline forms. So you better do a check if the self.instance attribute exist.

class GoalForm(forms.ModelForm):

   class Meta:
       model = Goal

   def __init__(self, *args, **kwargs):
       super(GoalForm, self).__init__(*args, **kwargs)
       if self.instance:
           self.fields['goal_scorer'].queryset = \
Player.objects.filter(gameroster__game=self.instance.game)
       else:
           ???????

also what you want to do is tricky. I think this post may refer to what you are trying to achieve.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号