django - 内联表单中的自定义表单

标签 django django-models django-admin django-forms

我有一个自定义表单来显示目标。 目标在游戏中内嵌编辑。

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',)

只要我“独立”编辑它,我的自定义表单就可以工作。 一旦我内联编辑它,自定义表单就会被忽略。 在类 GoalInline 的参数形式中进行注释会导致 Django 崩溃。

知道如何内联使用自定义表单吗?

最佳答案

我不认为管理员在实例化内联表单时总是传递实例关键字。所以你最好检查一下 self.instance 属性是否存在。

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

而且你想做的事情也很棘手。我认为this post可能指的是您想要实现的目标。

关于django - 内联表单中的自定义表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1559690/

相关文章:

python - django.core.exceptions.ImproperlyConfigured : The SECRET_KEY setting must not be empty

django - 确定 django-mptt 中每个级别的 "last"元素

python - psycopg2.errors.UndefinedTable : relation "authentication_author" does not exist: Django v4

django - Django-用户管理员-将组添加到list_display

django - 已在/admin/注册 Django 1.2 错误

python - Django 从字符字段迁移到整数字段?

html - Django 表单 - 禁用自定义 css 的错误转义

python - Errno - 13 权限被拒绝 : '/media/- Django

python - 无法使用 ChoiceField 检查表单值

python - "No action selected"删除对象时说Django-admin