10👍
✅
The problem here is that the avatar
ForeignKey field on your model is expecting to receive an instance of the wagtailimages.Image
model. The ImageField
on the form isn’t capable of providing this – it only provides a file object. To make this work, you’ll need to set up your form (which I’m assuming is a ModelForm) to create the wagtailimages.Image
object at the same time as your own model. It should be possible to do this with a custom save
method as follows:
- Rename
avatar = forms.ImageField
to something that doesn’t clash with theavatar
model field, such asavatar_image
- Ensure that
avatar_image
is included in your ModelForm’sfields
definition, butavatar
isn’t. At this point,avatar_image
is just an extra field on the form, with no connection to the model. -
Define the following
save
method on the ModelForm:from wagtail.images.models import Image def save(self, commit=False): if not commit: raise Exception("This form doesn't support save(commit=False)") # build the instance for this form, but don't save it to the db yet instance = super(MyForm, self).save(commit=False) # create the Image object avatar = Image.objects.create( file=self.cleaned_data['avatar_image'], title="Image title" # you may need to add more fields such as collection to make it a valid image... ) # attach the image to your final model, and save instance.avatar = avatar instance.save() return instance
Source:stackexchange.com