【发布时间】:2010-11-01 00:36:00
【问题描述】:
好的,我很难解释这一点,让我知道是否应该向您提供更多详细信息。
我的网址如下所示:http://domain.com/<category>/
每个<category> 可能有一个或多个子类别。
我希望类别页面有一个包含类别子类别的选择框(以及其他字段)的表单。 我目前在其中一个模板中对表单进行了硬编码,但我想让它直接反映模型。
在我当前的硬编码解决方案中,我的类别视图中有:
s = Category.objects.filter(parents__exact=c.id)
表单模板遍历并打印出选择框(参见下面的模型代码)
我猜我想要一个带有 init 过滤类别的 ModelFormSet,但我似乎无法在文档中找到如何做到这一点。
我也在查看How do I filter ForeignKey choices in a Django ModelForm?,但我无法让它正常工作。
我的模型
# 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
【问题讨论】:
标签: django django-models django-forms