根据选择刷新下拉菜单-Django Smartmin

时间:2018-10-29 06:54:47

标签: python django django-smart-selects

我们有类似的模型:

Class District:
   name = models.CharField()

Class Village:
  name = model.CharField()
  district = models.Foriegnkey()

Class Location:
  name = models.CharField()
  village = models.Foreginkey()

我们将Smartmin用于CRUD操作。在创建位置时,在我的表单中,我们显示地区,村庄下拉列表和名称字段(位置名称)。我需要根据地区选择刷新村庄。

在这方面请帮助我。预先感谢

1 个答案:

答案 0 :(得分:0)

在一个类似的项目中,我使用了django-autocomplete-light:https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html,它可以从一个下拉菜单到另一个下拉菜单进行级联选择。

我按如下方式使用它:

在forms.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'])
    )

在views.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'),
]