django-mptt and ForeignKey with blank=True
I am using django-mptt in my project
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)
开发者_Python百科
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)
The problem is -- I can't choose no parent, TreeNodeChoiceField doesn't show '---' in select. What could you recommend?
Use required=False
when initializing the TreeNodeChoiceField object.
field = TreeNodeChoiceField(
required=False,
queryset=Category.objects.all(),
level_indicator = u'+--',
)
Django form fields default to required=True
, in this case that means disallowing None as a value.
精彩评论