好吧,我很难解释这个,让我知道我是否应该向你补充更多细节。
我的网址如下所示:http<category
://domain.com/ >/
每个<category
> 可能有一个或多个子类别。
我希望类别页面有一个包含类别子类别的选择框(以及其他字段)的表单。我目前在其中一个模板中对表单进行了硬编码,但我想让它直接反映模型。
在我当前的硬编码解决方案中,我的类别视图中有:
s = Category.objects.filter(parents__exact=c.id)
表单模板迭代并打印出选择框(参见下面的模型代码)
我猜我想要一个带有init的 ModelFormSet过滤掉类别,但我似乎无法在文档中找到如何做到这一点。
一直在看如何在 Django ModelForm 中过滤 ForeignKey 选择?也一样,但我无法让它正常工作。
我的模型
# The model that the Form should implement
class Incoming(models.Model):
cat_id = models.ForeignKey(Category)
zipcode = models.PositiveIntegerField()
name = models.CharField(max_length=200)
email = models.EmailField()
telephone = models.CharField(max_length=18)
submit_date = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=False)
# The categories, each category can have none or many parent categories
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField()
parents = models.ManyToManyField('self',symmetrical=False, blank=True, null=True)
def __unicode__(self):
return self.name
我的表格
class IncomingForm(ModelForm):
class Meta:
model = Incoming