I’m trying to use a forms.MultipleChoiceField in Django, and form.is_valid returns True, but the query in my views.py returns “matching query does not exist.”
forms.py:
LIST_INTERESTS = (
('Energy', 'Energy'),
('Business', 'Business'),
('Social', 'Social'),
('Mobile', 'Mobile'),
)
interests = forms.MultipleChoiceField(choices=LIST_INTERESTS, initial='Energy')
views.py:
temp_interests = list(form.cleaned_data['interests']),
for i in temp_interests:
b = Interests.objects.get(val=i)
…at which point it will complain that something matching the query does not exist. Any ideas?
Bonus info:
When I plugged temp_interests into debug.html:
{% for i in temp_interests %}
{{ i }}<br>
{% endfor %}
it returns [u’Answer 1′, u’Answer 2′]
The problem lies in this line:
in the
get()method.I am not sure what you are trying to achieve here. but what
get()method does is returns a single matching query using the arguments passed. If it is not able to find any object using the arguments passed it raises theDoesNotExistexception, and that is what is happening in your case.[NOTE: Also, make sure you use the
get()when you are sure that there is only one object that exists according to the arguments passed. If you are not sure you can use thefilter()method which returns a list of all the objects that matches the given query.]You need to make sure that an
Interestobject exists wherevalattribute is equal to the value you are passing. So in the above case, there is noInterestobject wherevalis equal toi‘s value and hence the Exception is raised.To debug the above you can add a print statement as follows:
and check the server to see which
valuethe exception is being raised on.