【问题标题】:Need help with Django ModelForm: How to filter ForeignKey/ManyToManyField?在 Django ModelForm 方面需要帮助:如何过滤 ForeignKey/ManyToManyField?
【发布时间】: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


    【解决方案1】:

    正如你所说,你需要一个带有自定义 __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)
    

    【讨论】:

    • 我已经设法让它工作了!我几乎有你的代码,但它拒绝工作:) 它应该说 self.fields['cat_id']... :)
    • 我在这里遇到错误未定义的变量实例。当我使用 self.instance.id 时,我得到“无”。我不知道出了什么问题。
    【解决方案2】:

    我会编辑 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)
    

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

    【讨论】:

    • 我在这里遇到错误未定义的变量实例。当我使用 self.instance.id 时,我得到“无”。我不知道出了什么问题。
    猜你喜欢
    • 2012-04-29
    • 2010-09-22
    • 2012-04-04
    • 1970-01-01
    • 2011-01-27
    • 2014-02-06
    • 2017-11-02
    相关资源
    最近更新 更多