在Django ModelForm方面需要帮助:如何过滤ForeignKey/ManyToManyField?

sch*_*ick 5 django django-models django-forms

好吧,我很难解释这一点,请告诉我是否应该向您介绍更多细节.

我的网址如下所示:http://domain.com/<category >/
Each <category>可能有一个或多个子类别.

我希望类别页面具有包含类别子类别的选择框(以及其他字段)的表单.我目前在其中一个模板中对表单进行了硬编码,但我想让它直接反映模型.

在我目前的硬编码解决方案中,我在我的类别视图中:

s = Category.objects.filter(parents__exact=c.id)  
Run Code Online (Sandbox Code Playgroud)

表单模板迭代并打印出选择框(请参阅下面的模型代码)

我猜我想要一个带有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
Run Code Online (Sandbox Code Playgroud)

我的表格

class IncomingForm(ModelForm):
    class Meta:
        model = Incoming
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 9

如你所说,你需要一个带有自定义的modelform类__init__:

class IncomingForm(ModelForm):
    class Meta:
        model = Incoming

    def __init__(self, *args, **kwargs):
        super(IncomingForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['parents'].queryset = Category.objects.filter(
                                              parents__exact=instance.id)
Run Code Online (Sandbox Code Playgroud)


sch*_*ick 6

我会编辑Daniel Rosemans的回复并投票给它赢家,但由于我无法编辑它,我会在这里发布正确答案:

class IncomingForm(ModelForm):
    class Meta:
        model = Incoming

    def __init__(self, *args, **kwargs):
        super(IncomingForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['cat_id'].queryset = Category.objects.filter(
                    parents__exact=self.instance.id)
Run Code Online (Sandbox Code Playgroud)

区别是self.fields ['cat_id'](正确)vs self.fields ['parents'](错误,我们都犯了同样的错误)