I need to be able to both:
(a) prefilter dropdown lists for existing entries (to avoid loading unneeded
data);
(b) allow pre-filtered dropdown lists to change dynamically at runtime

I have, for example:

class Country(models.Model):
    id = models.CharField(max_length=2, primary_key=True)
    name = models.CharField(max_length=100, unique=True)

class Region(models.Model):
    id = models.AutoField(primary_key=True, )
    name = models.CharField(max_length=250, unique=True)
    country = models.ForeignKey(Country)

class Landmark(models.Model, ViewModel):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250)
    country = models.ForeignKey(Country)
    region = models.ForeignKey(Region)

Obviously, the regions exist within countries so, for a given Landmark, the
region list should be filtered for the chosen country.

I first used the texotela jQuery plugin (
http://www.texotela.co.uk/code/jquery/select/) to do the filtering.  The
code looks like this:

$(document).ready(function() {
    $("#id_country").change(function() {
        alert('country change...'); //test only
        var country_code = $(this).val();
        $("#id_region").removeOption(/./);
        $("#id_region").ajaxAddOption(region_url, {country: country_code},
false);
    });
});

This code works well.

The problem arises when existing records are edited.  Here the region list
shows up not filtered (I tried to add more jQuery code to filter after
loading, but it was messy and still did not avoid the problem that ALL the
regions are first loaded, which in turn makes the real form's HTML code
unnecessarily large...).

I then added an extra option to pre-filter the dropdown, using the modelform
approach - for more on this see
http://www.stereoplex.com/blog/filtering-dropdown-lists-in-the-django-adminand
http://www.artfulcode.net/articles/runtime-choicefield-filtering-in-djangos-admin.

The extra code looks like this:

class LandmarkModelForm(forms.ModelForm):
    class Meta:
        model = Landmark
    def __init__(self, *args, **kwargs):
        super(LandmarkModelForm, self).__init__(*args, **kwargs)
        if kwargs.has_key('instance'):
            _country = kwargs['instance'].country
            if _country:
                self.fields['region'].queryset = Region.objects.filter(
                    country=_country).order_by('name')

(with, of course, a corresponding entry in the admin.py to specify that the
above form is being used).

This also works in the sense that the regions are now pre-filtered to match
the country that has already been selected for the Landmark.

However, the problem comes when the country is changed.  The new set of
regions show up fine, thanks to the jQuery, but when I try and save the
form, I get the error "Select a valid choice. That choice is not one of the
available choices."  and the dropdown list for the regions has been reset
back to the pre-filtered set.

I'd appreciate any ideas or insights as to how to get both of these
"technologies" working smoothly together.

Thanks
Derek

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to