根据用户权限,在django admin中隐藏部分字段集的正确方法

时间:2018-12-12 10:55:44

标签: python django

我想在django admin中隐藏部分字段集,具体取决于用户权限。我已经通过重写get_fieldsets方法解决了这个问题,但是现在感觉这不是正确的方法。还有其他实现方法吗?

models.py

class Employee(models.Model):
    permitted_fields = {
        '{app_label}.can_edit_hidden_{model_name}': [
             'field1', 'field2']
    }

    first_name = models.CharField(_('First name'), max_length=255)
    last_name = models.CharField(_('Last name'), max_length=255)
    field1 = models.CharField(_('Field1'), max_length=255, null=True, blank=True)
    field2 = models.CharField(_('Field2'), max_length=255, null=True, blank=True)

    class Meta:
        permissions = (
            ('can_edit_hidden_employee',
            _('Can edit hidden fields'))
        )

admin.py

class EmployeeAdminForm(ModelForm):
    field1 = forms.CharField(label=_('field1'), required=False, widget=CustomWidget())
    field2 = forms.CharField(label=_('field2'), required=False, widget=CustomWidget())


class EmployeeAdmin(ModelAdmin):
    list_display = ('last_name', 'first_name')
    list_display_links = ('last_name', 'first_name')
    search_fields = (
        'first_name', '^last_name')

    fieldsets = ((
        None,
        {'fields': (
            'last_name', 'first_name')}
    ), )

    form = EmployeeAdminForm

    def get_fieldsets(self, request, obj=None):
        fieldsets = super(EmployeeAdmin, self).get_fieldsets(request, obj)
        if not request.user.has_perm('myapp.can_edit_hidden_employee'):
            return fieldsets
        return fieldsets + ((
            _('Hidden fields'),
            {'fields': ('field1', 'field2')}
        ), )

Django 1.11.17,python 3.7

0 个答案:

没有答案