django Forgienkey字段 在前台用js做处理
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),
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。