views:

75

answers:

2

I want to build a Country/State selector. First you choose a country, and the States for that country are displayed in the 2nd select box. Doing that in PHP and jQuery is fairly easy, but I find Django forms to be a bit restrictive in that sense.

I could set the State field to be empty on page load, and then populate it with some jQuery, but then if there are form errors it won't be able to "remember" what State you had selected. I'm also pretty sure that it will throw a validation error because your choice wasn't one of the ones listed in the form on the Python side of things.

So how do I get around these problems?

+1  A: 

You could set a hidden field to have the real "state" value, then use jQuery to create the <select> list and, on .select(), copy its value to the hidden field. Then, on page load, your jQuery code can fetch the hidden field's value and use it to select the right item in the <select> element after it's populated.

The key concept here is that the State popup menu is a fiction created entirely in jQuery and not part of the Django form. This gives you full control over it, while letting all the other fields work normally.

EDIT: There's another way to do it, but it doesn't use Django's form classes.

In the view:

context = {'state': None, 'countries': Country.objects.all().order_by('name')}
if 'country' in request.POST:
    context['country'] = request.POST['country']
    context['states'] = State.objects.filter(
        country=context['country']).order_by('name')
    if 'state' in request.POST:
        context['state'] = request.POST['state']
else:
    context['states'] = []
    context['country'] = None
# ...Set the rest of the Context here...
return render_to_response("addressform.html", context)

Then in the template:

<select name="country" id="select_country">
    {% for c in countries %}
    <option value="{{ c.val }}"{% ifequal c.val country %} selected="selected"{% endifequal %}>{{ c.name }}</option>
    {% endfor %}
</select>

<select name="state" id="select_state">
    {% for s in states %}
    <option value="{{ s.val }}"{% ifequal s.val state %} selected="selected"{% endifequal %}>{{ s.name }}</option>
    {% endfor %}
</select>

You'll also need the usual JavaScript for reloading the states selector when the country is changed.

I haven't tested this, so there are probably a couple holes in it, but it should get the idea across.

So your choices are:

  • Use a hidden field in the Django form for the real value and have the select menus created client-side via AJAX, or
  • Ditch Django's Form stuff and initialize the menus yourself.
  • Create a custom Django form widget, which I haven't done and thus will not comment on. I have no idea if this is doable, but it looks like you'll need a couple Selects in a MultiWidget, the latter being undocumented in the regular docs, so you'll have to read the source.
Mike DeSimone
That's a clever idea. Seems a tiny bit dirty, but I can live with it.
Mark
It's not dirty if it's properly documented. ^_-
Mike DeSimone
Just doesn't seem like I should need to have a hidden element to get around some of Django's quirks.
Mark
Django doesn't really do mutating forms. Whenever I have one, I just do the form myself.
Mike DeSimone
Not too fond of your edit either, although it is workable :p I'll stick with the hidden input/AJAX sol'n for now.
Mark
A: 

Based on Mike's suggestion:

// the jQuery
$(function () {
        var $country = $('.country');
        var $provInput = $('.province');
        var $provSelect = $('<select/>').insertBefore($provInput).change(function() {
                $provInput.val($provSelect.val());      
        });
        $country.change(function() {
                $provSelect.empty().addClass('loading');
                $.getJSON('/get-provinces.json', {'country':$(this).val()}, function(provinces) {
                        $provSelect.removeClass('loading');
                        for(i in provinces) {
                                $provSelect.append('<option value="'+provinces[i][0]+'">'+provinces[i][1]+'</option>');
                        }
                        $provSelect.val($provInput.val()).trigger('change');
                });
        }).trigger('change');
});

# the form
country = CharField(initial='CA', widget=Select(choices=COUNTRIES, attrs={'class':'country'}))
province = CharField(initial='BC', widget=HiddenInput(attrs={'class':'province'}))

# the view
def get_provinces(request):
    from django.utils import simplejson
    data = {
        'CA': CA_PROVINCES,
        'US': US_STATES
    }.get(request.GET.get('country', None), None)
    return HttpResponse(simplejson.dumps(data), mimetype='application/json')
Mark
Hmm... haven't passed a function to jQuery yet, so I'm not sure what that does. Usually I see `(function($){...})(jQuery);` for when you want `$` to be something other than `jQuery`. Also, in the `for (i in provinces)` loop I would use `$('<option/>').val(provinces[i][0]).text(provinces[i][1]).appendTo($provSelect);`. I'm guessing my way is slower, but it's easier to read when you put the clauses on one line each. Also, IIRC, you can use `$('#id_country')` instead of `$('.country')`; same for the province widget, which could let you dump the `class` stuff in the form.
Mike DeSimone
@Mike: `$(function()` is short-hand for `$(document).ready(function()`. I'm deliberately using a class because there might be multiple country/province selectors on one page... not that this script will work with multiple ones as is.
Mark