Custom form inline form

I have a custom form for displaying goals. Goals are edited inline in the 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',)

My user form works as long as I edit it "offline". As soon as I edit it in a line, the user form will be ignored. Commenting in the form of a parameter of the GoalInline class causes Django to crash.

Any idea how to use a custom inline form?

+3
source share
1 answer

I don't think admin always passes the instance keyword when instantiating inline forms. Therefore, you better check to see if the self.instance attribute exists.

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:
           ???????

, , . , , .

+1

Source: https://habr.com/ru/post/1719970/


All Articles