A
A
Andrey2015-01-31 20:38:18
Django
Andrey, 2015-01-31 20:38:18

How to do tree SELECTs in DjangoAdmin and FormModel using MPTT?

Good time of the day!
New to Django and Python. Got a question.
There is a model using MPTT to describe the tree structure of company divisions.

class Department (MPTTModel):
    title = models.CharField(max_length=500, verbose_name='Названием')
    abbreviation = models.CharField(max_length=25, verbose_name='Кратко', blank=True)
    parent = TreeForeignKey('self', blank=True, null=True, verbose_name='Родитель', related_name='child')
    class MPTTMeta:
        order_insertion_by = ['title']
    def dep_tree(self):
        return str(self.get_ancestors())
    def __str__(self):
        return self.title

class Employee (models.Model):
    common_name = models.CharField (max_length = 300, verbose_name='ФИО')
    department = models.ForeignKey (Department, verbose_name='Подразделение', null=True, blank=True)
   ...
mptt.register(Department,)

When manually creating a form, I use the TreeNodeChoiceField from MPTT to edit the Employee entities. As a result in the form in SELECT I will get a tree structure. (used indented -"--"). Everything is clear everything works.
class MyForm (forms.Form):
    Department = TreeNodeChoiceField(required=False, queryset=Department.objects.all(), level_indicator = u'---',)

But it would be desirable, that to SELECT'am in forms of an adminka and in automatically created forms. The deparment field used a TreeNodeChoiceField. Those. at the moment everything is flat in the admin panel, and in forms based on ModelForm too
class EmployeeForm (ModelForm):
    class Meta:
        model = Employee
        fields = ['common_name', 'department', 'position', 'address', 'work_phone', 'cell_phone', 'ip_phone']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Scherbakov, 2015-01-31
@Altaisoft

You can set the department field in EmployeeForm just like you did in MyForm . An alternative is the formfield_overrides attribute in the ModelAdmin .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question