我们有以下型号:
Class District:
name = models.CharField()
Class Village:
name = model.CharField()
district = models.Foriegnkey()
Class Location:
name = models.CharField()
village = models.Foreginkey()
我们正在使用Smartmin进行CRUD操作。创建地点时,在我的表格中,我们显示District、Village下拉列表和name字段(地点名称(。我需要根据地区选择来更新村庄。
请在这方面帮助我。提前感谢
在一个类似的项目中,我使用了django自动完成灯:https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html,它可以从一个下拉列表到另一个下拉菜单进行级联选择。
我使用它如下:
形式.py:
class TripModelForm(forms.ModelForm):
plate_number = forms.ModelChoiceField(
queryset=TruckUnit.objects.all().order_by('plate_number'),
widget=autocomplete.ModelSelect2(url='plate_number_autocomplete',
forward=['hauler'])
)
driver = forms.ModelChoiceField(
queryset=Driver.objects.all().order_by('name'),
widget=autocomplete.ModelSelect2(url='driver_autocomplete',
forward=['hauler'])
)
在视图中.py:
from dal import autocomplete
class PlateNumberAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return TruckUnit.objects.none()
qs = TruckUnit.objects.all().order_by('plate_number')
hauler = self.forwarded.get('hauler', None)
if hauler:
qs = qs.filter(hauler=hauler)
if self.q:
qs = qs.filter(plate_number__istartswith=self.q)
return qs
class DriverAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return Driver.objects.none()
qs = Driver.objects.all().order_by('name')
hauler = self.forwarded.get('hauler', None)
if hauler:
qs = qs.filter(hauler=hauler)
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
在urls.py中
urlpatterns += [
path('plate-number-autocomplete/', views.PlateNumberAutocomplete.as_view(), name='plate_number_autocomplete'),
path('driver-autocomplete/', views.DriverAutocomplete.as_view(), name='driver_autocomplete'),
]