Answer the question
In order to leave comments, you need to log in
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,)
class MyForm (forms.Form):
Department = TreeNodeChoiceField(required=False, queryset=Department.objects.all(), level_indicator = u'---',)
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
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 questionAsk a Question
731 491 924 answers to any question