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?
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.