[Answered ]-How to select box value can be change in django?

2๐Ÿ‘

โœ…

You need to use little bit of AJAX/JQuery.

#models.py
class Country(models.Model):
     country = models.CharField(max_length=20)

class State(models.Model):
    state = models.Charfield(max_length=20)
    country = models.ForeignKey(state)

#views.py
def filter (request):
    try:
        kwargs = {smart_str('country'): request.GET['q']}
    except KeyError:
        raise Http404
    qs = State.objects.filter(**kwargs).values('pk', 'name')
    response = HttpResponse(
        content=dumps(list(qs)),
        mimetype='application/json'
    )
    return response



#urls.py
urlpatterns = patterns('',
         url(r'^locations/filter/state-by-country/$', 'filter',  name='state_filter')
        ...
)

Add this to your template

//JQuery chained select plugin
$(function() {
  $('#id_state').chainedSelect({
    parent: '#id_country',
    url: 'locations/filter/find-by-country',
    value: 'id',
    label: 'name'
  });
});

0๐Ÿ‘

This question has been asked several times.

One example is here:
Conditional field in form

I have done it like this:
1) Create js script, that triggerst form GET request on select change.

2) In the view, you pass request.GET to form, instead of request.POST

3) In form init method you update the possible values of second field โ€“ see example.

4) View returns the page again where first select is set and 2nd select only has options, that first select allows.

Leave a comment