Django ModelForm过滤ForeignKey

时间:2013-09-02 10:55:23

标签: django forms filter modelform

我有这个:

在models.py

class Category(models.Model):
    Name = models.CharField(max_length=50)
    Description = models.CharField(max_length=150)

    def __unicode__(self):
        return self.Description

class Subcategory(models.Model):
    Category = models.ForeignKey(Category)
    Name = models.CharField(max_length=50)
    Description = models.CharField(max_length=150)

    def __unicode__(self):
        return self.Description

class Smartgrid(models.Model):
    Category = models.ForeignKey(Category)
    Subcategory = models.ForeignKey(Subcategory)
    Descriptor = models.CharField(max_length=150)

    def __unicode__(self):
        return self.Descriptor

在forms.py中:

class SmartgridForm(forms.ModelForm):
    class Meta:
        model = Smartgrid

在views.py

def new_point(request):
    if request.method=='POST':
        form = SmartgridForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/gis')
    else:
        form = SmartgridForm()

    return render_to_response('SmartgridForm.html', {'form':form}, context_instance=RequestContext(request))

问题:

我想要一旦用户在SmartgridForm.html中选择类别,子类别字段只显示这些子类别,其中category = category selected

谢谢!!!!

JDC。

1 个答案:

答案 0 :(得分:0)

如果您不想使用其他应用,则可以使用此解决方案:Django/jQuery Cascading Select Boxes?

但对我来说,使用Dajax更好 http://www.dajaxproject.com/forms/