我在我的项目中使用 django-mptt
模型.py:
class Category(models.Model):
name = models.TextField()
parent = models.ForeignKey("self", blank=True, null=True,
related_name="sub_category")
image = models.ImageField(upload_to="categories", blank=True)
mptt.register(Category)
管理员.py:
class CategoryAdmin(MPTTModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'parent':
field = TreeNodeChoiceField(
queryset=Category.objects.all(),
level_indicator = u'+--',
)
else:
field = super(CategoryAdmin, self).formfield_for_dbfield(
db_field, **kwargs)
return field
admin.site.register(Category, CategoryAdmin)
问题是——我不能选择没有父级,TreeNodeChoiceField 在选择中没有显示'---'。你能推荐什么?