如何禁用某些模型管理员中mptt的TreeForeignKey字段的Select小部件中的某些选项?

时间:2013-01-31 18:49:38

标签: django django-mptt

MyModel有一个mpt TreeForeignKey字段category。在MyModel的管理员中,如何在此Select字段的category窗口小部件中停用某些选项?

谢谢你

class Category(MPTTModel):
    parent = TreeForeignKey('self', blank=True, null=True, related_name='children')
    nom = models.CharField(max_length=100)

class MyModel(models.Model):
    category = TreeForeignKey(Category)
    # more fields

1 个答案:

答案 0 :(得分:9)

我不得不覆盖MyModelAdminForm,并为forms.ChoiceField字段使用category字段和SelectWithDisabled小部件。在我的情况下,我只希望树的叶子是可选择的。

class MyModelAdminForm(forms.ModelForm):

    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        self.level_indicator = kwargs.pop('level_indicator', u'---')
        super(MyModelAdminForm, self).__init__(*args, **kwargs)

        queryset = Category.objects.all()
        mptt_opts = queryset.model._mptt_meta
        queryset = queryset.order_by(mptt_opts.tree_id_attr, mptt_opts.left_attr)

        choices = []
        for item in queryset:
            level = getattr(item, item._mptt_meta.level_attr)
            value = item.id
            label = mark_safe(conditional_escape(self.level_indicator) * level + smart_unicode(item.nom))
            if item.is_leaf_node():
                choices.append((value, label))
            else:
                choices.append((value, {'label': label, 'disabled': True}))

        self.fields['category'] = forms.ChoiceField(choices=choices, widget=SelectWithDisabled)


class MyModelAdmin(admin.ModelAdmin):
    form = MyModelAdminForm

samsic_site.register(MyModel, MyModelAdmin)