Django ModelForm ValueError

337 views Asked by At

I have a Django Model

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    def __unicode__(self):
        return self.name
    class MPTTMeta:
        order_insertion_by = ['name']

and ModelForm

class UploadForm(ModelForm):
   file = forms.FileField()
   category = mpttform.TreeNodeMultipleChoiceField(queryset=Category.objects.filter(lft=F('rght')-1))
   class Meta:
         model = UploadedFile

However, I'm having problem with this category field in UploadForm which is supposed to be Category instance (as definied in Model), but my queryset return list of Category objects which I use in template to show all leaf categories.If I select any category on the form and submit it, I get this error(in case I select cat5) 'Cannot assign [Category: cat5]: "UploadedFile.category" must be a "Category" instance.' So I understand why this error is happening, but I'd like to use ModelForm because of save() method, but don't see how I can fix this.Any suggestions?

2

There are 2 answers

0
eusid On

Django is telling you that you must initiate a category instance in order to iterate over the categories. So the category instance takes params from the url, url params with regex in your urls.py . So you need to capture the param and make it the category instance in the view.

*See class based generic views for which views automatically give you the params context variable.

1
JoseP On

I think

category = mpttform.TreeNodeMultipleChoiceField(queryset=Category.objects.filter(lft=F('rght')-1))

Works for a m2m relation and I guess category is a ForeignKey in the model Uploaded File. If so, you should use

category = mpttform.TreeNodeChoiceField(queryset=Category.objects.filter(lft=F('rght')-1))