I have set a ForeignKey()
for class Town in the models file. Ideally, when I select a state, all towns belonging to this state will be listed in town.
#models.py
class State(models.Model):
state = models.CharField(max_length=50)
code = models.CharField(max_length=3)
def __str__(self):
return self.state
class Town(models.Model):
town = models.CharField(max_length=50)
code = models.CharField(max_length=4)
state = models.ForeignKey(State, on_delete=models.CASCADE)
def __str__(self):
return self.town
Now I can only use all()
in queryset to display all towns.
I feel like I should use filter()
, but I can't find a way to do it。
#forms.py
class Location(forms.Form):
state = forms.ModelChoiceField( required = True,
label = "State",
queryset = State.objects.all(),
widget = forms.Select(attrs = {
"class": "form-list-field"}
))
town = forms.ModelChoiceField( required = True,
label = "Town",
queryset = Town.objects.filter( ??? ).order_by('town'),
widget = forms.Select(attrs = {
"class": "form-list-field"}
))
CodePudding user response:
you can achieve this using
- Django forms
- ajax requests
forms.py
class Location(forms.Form):
state = forms.ModelChoiceField(
required=True,
label="State",
queryset=State.objects.all(),
widget=forms.Select(attrs={"class": "form-list-field"}),
)
town = forms.ModelChoiceField(
required=True,
label="Town",
queryset=Town.objects.none(),
widget=forms.Select(attrs={"class": "form-list-field"}),
) # need to populate this using jquery
now write a method in view to returning towns based on selected state
views.py
from django.http import HttpResponse
def get_towns(request, state_id):
state = State.objects.get(pk=state_id)
towns = Town.objects.filter(state=state)
towns_dict = {}
for town in towns:
towns_dict[town.id] = town.town
return HttpResponse(towns_dict, content_type='application/json')
in your html or API code make an ajax request to fetch the list of towns when an state is selected
CodePudding user response:
I already created mini project for achieving those things. It's called dependent drop-down
Plz clone this repo and run it.
Link is here