Reputation: 1116
i have two select box one is country
and another is state
. both value can be access to the database. I have select country select box then automatically another select box value change related to that country select box.
Example: I have select country india then automatically fetch the value states of another select box. I am using ajax get the value.
def constituency1(request):
country= Loksabha.objects.values('country_name').distinct('country_name')
terms = Loksabha.objects.values('lok_sabha').distinct('lok_sabha')
states=Loksabha.objects.values('state_name').distinct('state_name')
if 'p1' in request.GET and request.GET['p1']:
p1 = request.GET['p1']
states=Loksabha.objects.values('state_name').distinct('state_name').filter(country_name='p1')
if 'p2' in request.GET and request.GET['p2']:
p2 = request.GET['p2']
state_filter = Loksabha.objects.filter(state_name=p1,constituency_name=p2)
Upvotes: 1
Views: 428
Reputation: 8169
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'
});
});
Upvotes: 2
Reputation: 5656
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.
Upvotes: 0