django 下拉菜单三级联动 ,要详细的:models.py代码,urls.py代码,views.py 和html代码,及对应的数据库
时间: 2024-03-23 13:39:52 浏览: 145
好的,下拉菜单三级联动需要使用到Ajax技术,以下是一个简单的实现方法:
1. models.py
```python
from django.db import models
class Province(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class City(models.Model):
name = models.CharField(max_length=50)
province = models.ForeignKey(Province, on_delete=models.CASCADE)
def __str__(self):
return self.name
class District(models.Model):
name = models.CharField(max_length=50)
city = models.ForeignKey(City, on_delete=models.CASCADE)
def __str__(self):
return self.name
```
2. urls.py
```python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('ajax/load-cities/', views.load_cities, name='ajax_load_cities'),
path('ajax/load-districts/', views.load_districts, name='ajax_load_districts'),
]
```
3. views.py
```python
from django.http import JsonResponse
from .models import Province, City, District
def index(request):
provinces = Province.objects.all()
return render(request, 'index.html', {'provinces': provinces})
def load_cities(request):
province_id = request.GET.get('province')
cities = City.objects.filter(province_id=province_id).order_by('name')
return JsonResponse(list(cities.values('id', 'name')), safe=False)
def load_districts(request):
city_id = request.GET.get('city')
districts = District.objects.filter(city_id=city_id).order_by('name')
return JsonResponse(list(districts.values('id', 'name')), safe=False)
```
4. html代码
```html
<!DOCTYPE html>
<html>
<head>
<title>下拉菜单三级联动</title>
<meta charset="UTF-8">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<select id="id_province">
<option value="">请选择省份</option>
{% for province in provinces %}
<option value="{{ province.id }}">{{ province.name }}</option>
{% endfor %}
</select>
<select id="id_city">
<option value="">请选择城市</option>
</select>
<select id="id_district">
<option value="">请选择区县</option>
</select>
</form>
<script>
$(function() {
$('#id_province').change(function() {
var url = $('#id_province').attr('data-cities-url');
var provinceId = $(this).val();
$.ajax({
url: url,
data: {
'province': provinceId
},
success: function(data) {
var cities = $('#id_city');
cities.empty();
$.each(data, function(i, city) {
cities.append($('<option>').text(city.name).attr('value', city.id));
});
var districts = $('#id_district');
districts.empty();
districts.append($('<option>').text('请选择区县').attr('value', ''));
}
});
});
$('#id_city').change(function() {
var url = $('#id_city').attr('data-districts-url');
var cityId = $(this).val();
$.ajax({
url: url,
data: {
'city': cityId
},
success: function(data) {
var districts = $('#id_district');
districts.empty();
$.each(data, function(i, district) {
districts.append($('<option>').text(district.name).attr('value', district.id));
});
}
});
});
});
</script>
</body>
</html>
```
5. 数据库
此处省略。
阅读全文