Need help with Django ModelForm: how to filter ForeignKey / ManyToManyField?

Well, it's hard for me to explain this, let me know if I write you more details.

My url is as follows: http://domain.com/ <category > /
Each <category> may have one or more subcategories.

I want the category page to have a form with a selection field (among other fields) containing subcategories of the category. Currently, I have hardcoded the form in one of the templates, but I want it to reflect the model directly.

In my hard coded solution, I have categories in my view:

s = Category.objects.filter(parents__exact=c.id)  

so that the form template repeats and prints the selection field (see model code below)

I assume I want a ModelFormSet with init that filters out categories, but I cannot find how to do this in the docs.

Looked at How to filter ForeignKey options in Django ModelForm? but I can't get it to work correctly.

My models

# 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

My form

class IncomingForm(ModelForm):
    class Meta:
        model = Incoming
+5
source share
2 answers

I would edit Daniel Rosemany and vote for its winner, but since I cannot edit it, I will post the correct answer here:

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)

The difference is self.fields ['cat_id'] (right) vs self.fields ['parents'] (wrong, we both made the same mistake)

+6
source

, 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)
+9

All Articles