0

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?

eggbert
  • 3,105
  • 5
  • 30
  • 39

2 Answers2

1

Your model needs blank=True as well and null=True

location = models.ForeignKey(Location, blank=True, null=True)
school_type = models.ForeignKey(SchoolType, blank=True, null=True)

This post talks about blank and null.

Community
  • 1
  • 1
rockingskier
  • 9,066
  • 3
  • 40
  • 49
  • This still doesn't work: >>> form.errors {'school_type': [u'Select a valid choice. That choice is not one of the available choices.'], 'location': [u'Select a valid choice. That choice is not one of the available choices.']} – eggbert Apr 04 '14 at 14:13
  • you need to set 'empty_label' to "all" not `empty_values` – rockingskier Apr 04 '14 at 14:29
0

This worked in the end:

class SearchPreferenceForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SearchPreferenceForm, self).__init__(*args, **kwargs)
        self.fields['location'].empty_values.append('all')
        self.fields['school_type'].empty_values.append('all')
eggbert
  • 3,105
  • 5
  • 30
  • 39