我正在开发一个基于Django 1.4.5框架的Web应用程序。我想根据在另一个下拉列表中选择的选项(select id =“ida”)动态填充下拉列表中的选项(选择id =“packages”)。我一直在寻找答案,但没有任何东西指向正确的方向。这是我的代码:
我的模板(html):
function getPackages(elementId)
{
//This is what I want to write, but could not figure out.
}
Select IDA's:
<select id="ida" name="ida" onchange="getPackages('ida');">
{% for ida in ida_list %}
<option value="ida{{ ida.id }}">{{ ida.ida_display_name }}</option>
{% endfor %}
</select>
Select packages to install: <select id="package" name="package"multiple="multiple" size="5">
{% for package in package_list %}
<option value="package {{ package.pkg_id }}">{{ package.display_name }}</option>
{% endfor %}
</select>
我的观点:
def automation(request):
ida_list = IDA.objects.all()
ida = IDA.objects.get(ida_name='VSA') #this is what I want to do from javascript
package_list = ida.package_set.all()
context = {'ida_list' : ida_list, 'package_list' : package_list}
return render_to_response('vsawebauto/automation.html', context, context_instance=RequestContext(request))
我的模特:
class IDA(models.Model):
ida_name = models.CharField(max_length=100)
ida_display_name = models.CharField(max_length=100)
def __unicode__(self):
return self.ida_name
class Package(models.Model):
pkg_ID = models.IntegerField(primary_key=True)
pkg_name = models.CharField(max_length=50)
display_name = models.CharField(max_length=100)
username = models.CharField(max_length=50,default="NULL")
password = models.CharField(max_length=50,default="NULL")
IDAs = models.ManyToManyField(IDA)
def __unicode__(self):
return self.display_name
简要说明:根据html页面上的IDA选择,我希望包动态地显示在下拉列表中。包可以属于多个IDA,反之亦然(模型类中有许多关系)。所以,我希望只要用户选择IDA,javascript就应该获得与该IDA相对应的对象(例如:ida = IDA.objects.get(ida_name ='VSA')),并且应该为此获取包IDA并显示。
答案 0 :(得分:0)
好吧,我做了一段时间。
某些urls.py中的
#...
url(r'^package_ajax/$', PackageForIdaView.as_view(), name="ida_change_all"),
url(r'^package_ajax/(?P<pk>[-_\w]+)/$', PackageForIdaView.as_view()),
#...
在一些views.py
中class PackageForIdaView(ListView):
template_name = "partial/package_options.html"
model = Package
context_object_name = "package_list"
def get_queryset(self):
query_set = super(PackageForIdaView, self).get_queryset()
if 'pk' in self.kwargs:
query_set = query_set.filter(IDAs=self.kwargs['pk'])
return query_set
在某些javascript中:
$('#ida').change(function(event){
var url = "{% url "ida_change_all" %}";
var ida_id = this.value;
if ida_id != undefined:
url += ida_id
$('#package').load(url);
})
“package_options.html”模板中的:
{% for package in package_list %}
<option value="package {{ package.pkg_id }}">{{ package.display_name }}</option>
{% endfor %}
也许有些事情失败了,我不记得所有的细节,但这就是方法。
希望这有帮助!