1

我有形式:

class NewUserForm(forms.ModelForm):
    first_name = forms.CharField(label=u'First name', required=True)
    last_name = forms.CharField(label=u'Last name', required=True)
    permissions = forms.ModelMultipleChoiceField(Permission.objects.none(), widget=forms.CheckboxSelectMultiple)

    def __init__( self, *args, **kwargs ):
        super( NewUserForm, self ).__init__( *args, **kwargs )
        ctypes = ContentType.objects.filter(
            Q(app_label='articles') |
            Q(app_label='tags')
        )
        self.fields['permissions'].queryset = Permission.objects.filter(content_type__in=ctypes)

    class Meta:
        model = User

在模板权限中向我展示了这样的标签:

[] articles | article | Can change article
[] articles | article | Can delete article
[] articles | article | Can view article

[...]

如何更改此标签?我只想得到(例如):“可以更改文章”,也许是其他语言。

4

1 回答 1

3

您可以子类化ModelMultipleChoiceField并定义一个label_from_instance方法。

class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s" % obj.name # e.g. 'Can change article'

然后在表单中使用您的字段子类。

class NewUserForm(forms.ModelForm):
    ...
    permissions = MyModelMultipleChoiceField(Permission.objects.none(), widget=forms.CheckboxSelectMultiple)
    ...
于 2013-05-15T12:19:40.360 回答