You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django中实现基于文本框国家名称的州下拉框动态加载

Django实现国家输入与州/省下拉框联动功能

首先先修正你HTML代码里的小问题(比如标签拼写、文本与功能不匹配),调整后代码如下:

<div class="control-group">
    <label class="control-label pull-left" for="country">国家</label>
    <div class="controls">
         <input name="country_name" id="country-input" type="text" placeholder="输入国家名称">
    </div>
</div>
<div class="control-group">
    <label class="control-label pull-left" for="states">州/省</label>
    <div class="controls">
        <select name="states" id="states-select">
            <option value="">-----</option>
        </select>
    </div>
</div>

接下来分后端和前端两部分实现联动逻辑:

一、Django后端实现

1. 准备数据模型(如果还未定义)

假设你需要存储国家和州/省的关联数据,可定义如下模型:

from django.db import models

class Country(models.Model):
    name = models.CharField(max_length=100, unique=True)

class State(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states')

2. 编写视图函数

在对应app的views.py中,写一个处理请求的视图,根据传入的国家名称返回对应的州/省列表:

from django.http import JsonResponse
from .models import Country

def get_states(request):
    country_name = request.GET.get('country_name', '')
    states = []
    if country_name:
        try:
            # 忽略大小写匹配国家名称,可根据需求改成精确匹配(name=)
            country = Country.objects.get(name__iexact=country_name)
            states = [{'id': state.id, 'name': state.name} for state in country.states.all()]
        except Country.DoesNotExist:
            pass
    return JsonResponse({'states': states})

3. 配置URL路由

在项目或app的urls.py中添加路由,映射到上面的视图:

from django.urls import path
from . import views

urlpatterns = [
    # 其他已有路由...
    path('get-states/', views.get_states, name='get_states'),
]

二、前端JavaScript实现

提供两种常用方案,选一种适配你的项目即可:

方案1:原生JavaScript

在HTML页面底部添加脚本:

const countryInput = document.getElementById('country-input');
const statesSelect = document.getElementById('states-select');
let debounceTimer; // 防抖定时器,避免频繁请求

countryInput.addEventListener('input', function() {
    clearTimeout(debounceTimer);
    const countryName = this.value.trim();
    
    // 清空下拉框,保留默认选项
    statesSelect.innerHTML = '<option value="">-----</option>';
    if (!countryName) return;

    // 用户停止输入500ms后再发送请求,优化性能
    debounceTimer = setTimeout(() => {
        fetch(`/get-states/?country_name=${encodeURIComponent(countryName)}`)
            .then(response => response.json())
            .then(data => {
                data.states.forEach(state => {
                    const option = document.createElement('option');
                    option.value = state.id;
                    option.textContent = state.name;
                    statesSelect.appendChild(option);
                });
            })
            .catch(error => console.error('获取州/省数据失败:', error));
    }, 500);
});

方案2:jQuery(如果项目已引入jQuery)

$('#country-input').on('input', function() {
    const countryName = $(this).val().trim();
    $('#states-select').html('<option value="">-----</option>');
    
    if (!countryName) return;
    
    // 防抖处理
    clearTimeout($(this).data('timer'));
    $(this).data('timer', setTimeout(() => {
        $.get('/get-states/', { country_name: countryName }, function(data) {
            $.each(data.states, function(index, state) {
                $('#states-select').append(`<option value="${state.id}">${state.name}</option>`);
            });
        });
    }, 500));
});

额外说明

  • 如果担心用户输入的国家名称有拼写错误,建议把文本输入框改成国家下拉选择框,能进一步提升交互准确性,但如果需求必须是文本输入,当前方案完全适用。
  • 可根据业务需求调整后端的匹配逻辑,比如支持模糊匹配(用name__contains)。

内容的提问来源于stack exchange,提问作者Harika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:55:16