I have this model:
class SearchPreference(models.Model):
"""Saves the preferred location and school_type of the User
"""
user = models.OneToOneField(User, related_name='search_preference')
location = models.ForeignKey(Location, null=True)
school_type = models.ForeignKey(SchoolType, null=True)
class Meta:
app_label = 'grants'
and this form:
class SearchPreferenceForm(forms.ModelForm):
location = forms.ChoiceField(queryset=Location.objects.all(),
to_field_name='slug',
required=False)
school_type = forms.ChoiceField(queryset=SchoolType.objects.all(),
to_field_name='slug',
required=False)
class Meta:
model = SearchPreference
fields = ('location', 'school_type')
I am trying to use the form to do validation of POST data, I am not displaying it in a template.
The problem is, the POST data can include a value which isn't in the Location or SchoolType table, so the form doesn't validate. The value is 'all', signifying 'all locations' or 'all school types', and I really want this to be saved as a SearchPreference with no location, i.e. location = null.
I could change 'all' to an empty value and that might work but then validation/logic has moved out of the form.
I thought I could use empty_value = 'all' but this doesn't work on a modelChoiceField.
Is there any way of doing this?