32 lines
1.4 KiB
Python
32 lines
1.4 KiB
Python
from django import forms
|
|
|
|
from application.org_mgnt.models import PrimaryDepartment, SecondaryDepartment
|
|
|
|
|
|
class DepartmentSelectionForm(forms.Form):
|
|
primary_department = forms.ModelChoiceField(
|
|
queryset=PrimaryDepartment.objects.all(),
|
|
widget=forms.Select(attrs={'class': 'form-control'}),
|
|
empty_label="选择一级部门",
|
|
label="一级部门"
|
|
)
|
|
secondary_department = forms.ModelChoiceField(
|
|
queryset=SecondaryDepartment.objects.none(),
|
|
widget=forms.Select(attrs={'class': 'form-control'}),
|
|
empty_label="选择二级部门",
|
|
label="二级部门"
|
|
)
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super(DepartmentSelectionForm, self).__init__(*args, **kwargs)
|
|
if 'primary_department' in self.data:
|
|
try:
|
|
primary_department_id = int(self.data.get('primary_department'))
|
|
self.fields['secondary_department'].queryset = SecondaryDepartment.objects.filter(primary_department_id=primary_department_id).order_by('secondary_department_name')
|
|
except (ValueError, TypeError):
|
|
pass
|
|
elif 'instance' in kwargs and kwargs['instance']:
|
|
instance = kwargs['instance']
|
|
if hasattr(instance, 'primary_department'):
|
|
self.fields['secondary_department'].queryset = instance.primary_department.secondarydepartment_set.order_by('secondary_department_name')
|