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
答案 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)