我有表格:
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
[...]
如何更改此标签?我想得到(例如):“可以改变文章”,也许用其他语言。
答案 0 :(得分: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)
...