在我做的项目中有个选择省城市的选项,这两个字段的关系是一对多的关系
class Province(models.Model): # 省会
name = models.CharField(max_length=30)
class City(models.Model): #城市
name = models.CharField(max_length=30)
province = models.ForeignKey(Province)
前台代码:
<html>
<head>
<link rel="stylesheet" type="text/css" href="/site_media/css/imgareaselect-default.css" />
<script type="text/javascript" src="/site_media/scripts/jquery.min.js"></script>
<script type="text/javascript" src="/site_media/scripts/jquery.imgareaselect.pack.js"></script>
</head>
<form action="/addInfo/" method="post" name="" class="hform">
<fieldset>
<p><label><span style="color:red">*</span>选择分类</label>
<select name="province" id="province">
<option value="">请选择分类</option>
{% for province in provinces %}
<option value="{{ province.id }}">{{ province.name }}</option>
{% endfor %}
</select>
</p>
<p><label<span style="color:red">*</span>选择子类</label>
<select name="city" id="city">
</select>
</p>
<p><label><span style="color:red">*</span>标题</label>
<input type="text" name="title" id="title">
</p>
<p><input type="submit" name="submit" value="提交" class="button"></p>
</fieldset>
</form>
{% block js %}
<script lang="javascript">
$("#province").change(function (){
if($("#province").val() != ""){
$.getJSON("/getcity/", { category: $("#province").val() },
function(data){
$("#city").empty();
$("#city").append("<option value=\"\">请选择子类</option>");
if(data.length!=0){
$.each(data,function(i,n){
$("#city").append("<option value="+i+">"+n+"</option>");
});
}
});
}else{
$("#city").empty();
}
});
$("form").submit(function() {
if ($("#province").val() == "") {
alert("请选择分类");
$("#province").focus();
return false;
}
if ($("#city").val() == "") {
alert("请选择子类");
$("#city").focus();
return false;
}
});
后台:
def cityinfo(request):
provinces = Province.objects.all()
return render_to_response("cityform.html",locals())
def getcity(request):
provinceId = int(request.GET.get(‘category‘))
province = Province.objects.get(id=provinceId)
citys = City.objects.filter(province=province)
data = {}
for city in citys:
data[city.id] = city.name
return HttpResponse(simplejson.dumps(data))
urls.py
(r‘^province/$‘, views.cityinfo),
(r‘^getcity/$‘,views.getcity),
django Forgienkey字段 在前台用js做处理,布布扣,bubuko.com