当前位置: 动力学知识库 > 问答 > 编程问答 >

django - How to change labels for permissions?

问题描述:

I have form:

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

And in template permissions shows me labels something like this:

[] articles | article | Can change article

[] articles | article | Can delete article

[] articles | article | Can view article

[...]

How to change this labels? I want to get only (for example): "Can change article", maybe in other language.

网友答案:

You can subclass ModelMultipleChoiceField and define a label_from_instance method.

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

Then use your field subclass in your form.

class NewUserForm(forms.ModelForm):
    ...
    permissions = MyModelMultipleChoiceField(Permission.objects.none(), widget=forms.CheckboxSelectMultiple)
    ...
分享给朋友:
您可能感兴趣的文章:
随机阅读: