0

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)

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?

Eugene Nagorny
  • 1,626
  • 3
  • 18
  • 32

1 Answers1

1

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.

Michał Modzelewski
  • 1,320
  • 10
  • 8
  • 1
    it works. But for me seems strange. Why required dont taken from blank=True – Eugene Nagorny Jul 08 '11 at 14:03
  • @Ideviantik `blank=True` and `null=True` are values on the `Model` field. You as defining the `Form` field which has no knowledge of the `Model`. Normally a `ModelForm` or `ModelAdmin` get passed constructor arguments for the field based on the `Model` used, but in your code you are overriding this with a cusom field. the method `formfield_for_dbfield` takes the arguments `db_field` and `kwargs`. `kwargs` is a dictionary of all the keyword arguments Django wanted to pass to the field constructor. Check the contents of `kwargs` for `required=True` and other arguments you may have missed. – Michał Modzelewski Jul 09 '11 at 10:54