XH_Digital_Management/common/forms.py

38 lines
1.9 KiB
Python
Raw Permalink Normal View History

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') and isinstance(instance.primary_department, PrimaryDepartment):
self.fields['secondary_department'].queryset = instance.primary_department.secondarydepartment_set.order_by('secondary_department_name')
else:
try:
primary_department = PrimaryDepartment.objects.get(department_name=instance.primary_department)
self.fields['secondary_department'].queryset = primary_department.secondarydepartment_set.order_by('secondary_department_name')
except PrimaryDepartment.DoesNotExist:
self.fields['secondary_department'].queryset = SecondaryDepartment.objects.none()