django-mptt和ForeignKey,空白= True

时间:2011-07-08 11:10:50

标签: python django foreign-keys mptt

我在我的项目中使用django-mptt

models.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)

admin.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在select中不显示'---'。 你能推荐什么?

1 个答案:

答案 0 :(得分:1)

初始化TreeNodeChoiceField对象时使用required=False

field = TreeNodeChoiceField(
                            required=False,
                            queryset=Category.objects.all(),
                            level_indicator = u'+--',
                                    )

Django表单字段默认为required=True,在这种情况下,这意味着禁止将None作为值。