In my project there is a choice of provincial cities, the relationship between the two fields is a one-to-many relationship
Class Province (models. Model): # Capital
Name = models. Charfield (max_length=30)
Class city (models. Model): #城市
Name = models. Charfield (max_length=30)
Province = models. ForeignKey (province)
Front Code:
<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>
<form action= "/addinfo/" method= "post" name= "class=" Hform ">
<fieldset>
<p><label><span style= "color:red" >*</span> Select Category </label>
<select name= "province" id= "province" >
<option value= "" > Please select Category </option>
{% for province in provinces%}
<option value= "{{province.id}}" >{{Province.name}}</option>
{% ENDFOR%}
</select>
</p>
<p><label<span style= "color:red" >*</span> Select sub-class </label>
<select name= "City" id= "City" >
</select>
</p>
<p><label><span style= "color:red" >*</span> title </label>
<input type= "text" name= "title" id= "title" >
</p>
<p><input type= "Submit" name= "Submit" value= "Submission" 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=\" \ "> Please select sub-category </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 ("Please select category");
$ ("#province"). focus ();
return false;
}
if ($ ("#city"). val () = = "") {
Alert ("Please select Subclass");
$ ("#city"). focus ();
return false;
}
});
Background:
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),