Reputation: 43
I'm new to both python and django and now I've been struggling with this form for a while. What I got is a form with three fields. I want it to be possible to leave each of these fields blank and in the view I'm trying to make an if-elif-else statement depending on what fields that are left blank. It is here it goes wrong though.
If I leave field1 blank a is an empty list if i print it but in the if statement a == [ ] doesn't seem to count. It jumps direcltly to the else part where an error occurs at the random function since it can't be used on d (which is an empty list since it has been filtered with a).
Everything works fine if I don't leave any field in the form blank.
My questions: Is it not possible to do if statements on the cleaned data or am I just doing it all wrong? Why doesn't "if a == [ ]" count?
Here is how parts of the code looks. The view:
def SomeFunction(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
a = form.cleaned_data['field1']
b = form.cleaned_data['field2']
c = form.cleaned_data['field3']
form = form.save()
if a == []:
d = Model2.objects.filter(Model2field2=b, Model2field3=c).distinct()
e = random.choice(d)
return render(request, 'SomePage.html', {
'e' : e
})
#Here I have some similar elif statements..
else:
d = Model2.objects.filter(Model2field1=a, Model2field2=b, Model2field3=c).distinct()
e = random.choice(d)
return render(request, 'SomePage.html', {
'e' : e
})
The form:
class SomeForm(forms.ModelForm):
class Meta:
model = Model1
fields = ['field1', 'field2', 'field3']
widgets = {
'field1' : forms.CheckboxSelectMultiple,
'field2' : forms.CheckboxSelectMultiple,
'field3' : forms.CheckboxSelectMultiple,
}
Upvotes: 2
Views: 834
Reputation: 599788
You're checking if a is, specifically, an empty list. But that will never be true: the empty value for a ModelMultipleChoiceField (which is the field that is created for a ManyToManyField) is an empty queryset - see the documentation.
Instead, just use a boolean comparison:
if not a:
Upvotes: 1