0

我正在开发一个基于 Django 1.4.5 框架的 Web 应用程序。我想根据在另一个下拉列表中选择的选项(选择 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 并显示。

4

1 回答 1

0

Well, I made it some time.

in some urls.py

#...
url(r'^package_ajax/$', PackageForIdaView.as_view(), name="ida_change_all"),
url(r'^package_ajax/(?P<pk>[-_\w]+)/$', PackageForIdaView.as_view()),
#...

in some 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

in some 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);
})

in "package_options.html" template:

{% for package in package_list %}
    <option value="package {{ package.pkg_id }}">{{ package.display_name }}</option>
{% endfor %}

Maybe somethings fails,i don't remember all details, but that is the way.

Hope this helps!

于 2013-06-18T19:47:31.920 回答