Django Admin:stackedLine/tablarinlin中的默认值

2024-09-29 21:48:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个网站,它需要国际化的支持。默认语言为葡萄牙语、英语和西班牙语。我使用的是django-i18nmodel,到目前为止它运行得很好。在

当管理员想要使用django admin创建产品时,默认情况下,我会创建模型ProductI18N的3个内联项

class LanguageStackedInline(admin.StackedInline):
    model = ProductI18N
    extra = 1

我想用上面提到的默认语言(pt-pt,en-US,es-es)创建这3行。我知道在模型中我只能设置一个默认值。在

Django是否提供了一种简单的方法?在


Tags: django模型pt语言esadmin产品网站
2条回答

为内联管理员提供自定义窗体集类:

from django.forms.models import BaseInlineFormSet

class LanguageInlineFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super(LanguageInlineFormSet, self).__init__(*args, **kwargs)

        # Assuming the field you want to populate to is called "name"
        self.initial = [
            {'name': 'pt-PT'}, {'name': 'en-US'}, {'name': 'es-ES'}
        ]

class LanguageStackedInline(admin.StackedInline):
    model = ProductI18N
    extra = 3    # You said you need 3 rows
    formset = LanguageInlineFormSet

您可以查看有关admininline formsets的文档,了解有关自定义的更多说明。在

我要感谢天王星给了我这个解决方案的提示。他的回答对我不起作用,但以下是有效的:

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'键。在

{{cd2>在这里更详细地解释了cd2}:

https://docs.djangoproject.com/en/dev/topics/forms/formsets/#formsets-initial-data

因此,只需将其添加到重载构造函数中的kwargs中就可以了。在

编辑:让我也分享我在我的应用程序中实际使用的代码:

^{pr2}$

这将为每个非默认语言生成一个表单。它并不完美,因为它没有考虑到已经保存了一种非默认语言的情况,但它给了我一个很好的起点。在

相关问题 更多 >

    热门问题