我要感谢 uranusjr 给我这个解决方案的提示。他的回答对我不起作用,但这是有效的:
class LanguageInlineFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
kwargs['initial'] = [
{'name': 'pt-PT'}, {'name': 'en-US'}, {'name': 'es-ES'}
]
super(LanguageInlineFormSet, self).__init__(*args, **kwargs)
# Rest of the code as per @uranusjr's answer
class LanguageStackedInline(admin.StackedInline):
model = ProductI18N
extra = 3 # You said you need 3 rows
formset = LanguageInlineFormSet
我保留了'name'
密钥以便于比较。
为了更详细地解释,BaseInlineFormSet
采用initial
此处记录的参数:
https://docs.djangoproject.com/en/dev/topics/forms/formsets/#formsets-initial-data
所以简单地将它添加到kwargs
重载的构造函数中效果很好。
编辑:让我也分享一下我在我的应用程序中实际使用的代码:
from django.conf import settings
from django.forms.models import BaseInlineFormSet
from myapp.models import MyI18N
class MyI18NInlineFormset(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
kwargs['initial'] = [{'i18n_language': lang[0]}
for lang in settings.LANGUAGES
if lang[0] != settings.LANGUAGE_CODE]
super(MyI18NInlineFormset, self).__init__(*args, **kwargs)
class MyI18NInline(admin.StackedInline):
model = MyI18N
extra = max_num = len(settings.LANGUAGES) - 1
formset = MyI18NInlineFormset
这会为每种非默认语言生成一个表单。它并不完美,因为它没有考虑到已经保存了一种非默认语言的情况,但它给了我一个很好的起点。