Reputation: 454
I have a form where the options of one of my select input are related to another table.
Everything works perfectly, but know i want to exclude some options so i have the following kode in forms.py:
class employeesForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(employeesForm, self).__init__(*args, **kwargs)
self.fields['num_employee'].required = False
self.fields['id_ignition'].required = False
self.fields['picture'].required = False
self.fields['source'].required = False
class Meta:
model = Employees
ccOptions = CostCenter.objects.all().values_list('id_costCenter', 'area')
jcOptions = JobCode.objects.all().values_list('id_jobCode', 'gmpName')
ntOptions = Nations.objects.all().values_list('nationality')
esOptions = EmpSources.objects.all().values_list('source')
from django.db.models import Q
# in this line
stOptions = Status.objects.exclude(Q(id_status=2) | Q(id_status=3)).values_list('status')
fields = [
'num_employee',
'fullName',
'shortName',
'gender',
'birthday',
'initday',
'id_status',
'nationality',
'picture',
'source',
]
widgets = {
'num_employee': forms.NumberInput(attrs={'class': 'form-control', 'name': 'num_employee'}),
'fullName': forms.TextInput(attrs={'class': 'form-control', 'name': 'fullName', 'placeholder': 'Angel Rafael Ortega Vazquez'}),
'shortName': forms.TextInput(attrs={'class': 'form-control', 'name': 'shortName', 'placeholder': 'Rafael Ortega'}),
'gender': forms.CheckboxInput(attrs={'class': 'form-control', 'name': 'gender'}),
'birthday': forms.DateInput(attrs={'class': 'form-control', 'name': 'birthday'}),
'initday': forms.DateInput(attrs={'class': 'form-control', 'name': 'initday'}),
# also here
'id_status': forms.Select(choices=stOptions, attrs={'class': 'form-control', 'name': 'id_status'}),
'nationality': forms.Select(choices=ntOptions, attrs={'class': 'form-control', 'name': 'nationality'}),
'picture': forms.ClearableFileInput(attrs={'class': 'form-control', 'name': 'picture'}),
'source': forms.Select(choices=esOptions, attrs={'class': 'form-control', 'name': 'source'}),
}
The problem is that even with the exclude option, my select stills rendering the complete table.
I even tried filtering only one parameter but the result is the same. I also deleted my browser cache just to discard this possibility, but it didn't changed.
Upvotes: 0
Views: 44
Reputation: 11238
Related objects in ModelForms are ModelChoiceField
s. You need to specify the queryset=...
attribute.
Example:
class Department(models.Model):
name = models.CharField()
active = models.BooleanField()
class Employee(models.Model):
name = models.CharField()
department = models.ForeignKey(Department)
class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
exclude = []
def __init__(self, *args, **kwargs):
super(EmployeeForm, self).__init__(*args, **kwargs)
self.fields['department'].queryset = Department.objects.filter(active=True)
Upvotes: 1