django 如何设置表单中的查询集.Form(ModelChoiceField)的下拉城市列表?

klr1opcd  于 2022-12-20  发布在  Go
关注(0)|答案(2)|浏览(232)

我在models文件中为class Town设置了一个ForeignKey()。理想情况下,当我选择一个州时,所有属于这个州的城镇都会列在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

现在只能用queryset中的all()来显示所有的城镇,感觉应该用filter(),但是找不到办法。

#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"}
                                ))
hyrbngr7

hyrbngr71#

你可以使用

  1. Django形式
  2. AJAX 请求

表单.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

现在编写一个方法,以便根据选定的状态返回城镇

查看次数.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')

在您的html或API代码中,当选择一个州时,发出 AJAX 请求以获取城镇列表

zfciruhq

zfciruhq2#

我已经创建了一个小项目来实现这些事情。它被称为依赖下拉
请克隆此回购协议并运行它。
链接为here

相关问题