How to implement chained/related dropdown lists in a page

42 views
Skip to first unread message

Frankline

unread,
Oct 7, 2014, 3:04:35 PM10/7/14
to django...@googlegroups.com
I am interested in knowing how other developers implement chained dropdown lists that are dependent on one another. As an example, I have a page/form that has two dropdown lists. When I select a value from the first select, I want the second dropdown to be populated by records related to the first one. This is more of a Country/City situation. Below is how my models look like.

#models.py
class Category(models.Model):
    description = models.CharField(max_length=100)

class SubCategory(models.Model):
description = models.CharField(max_length=100)
    category = models.ForeignKey(Category)
    
I am guessing I will have to involve ajax in one way or the other. Anyone has an idea on how to implement this?

Collin Anderson

unread,
Oct 8, 2014, 8:44:56 AM10/8/14
to django...@googlegroups.com
I haven't done it much, but, yeah, ajax is probably best. Maybe something like might work:
$('#id_category').change(function(){
   
var category = $(this).val()  // not sure about this. the point is, get the selected id.
    $
.get('/subcategory-options/?category=' + encodeURIComponent(category), function(data){
        $
('#id_subcategory').replaceWith(data)
   
})
})

urls.py:
    url(r'^subcategory-options/$', views.subcategory_options),

views.py:
def subcategory_options(request):
    subcategories
= SubCategory.objects.filter(category=request.GET['category'])
   
class TempForm(forms.Form):
        field
= forms.ModelChoiceField(queryset=subcategories)
   
form = TempForm()
   
return render(request, 'subcategory_options.html', {'form': form})

subcategory_options.html:
{{ form }}

Reply all
Reply to author
Forward
0 new messages