I'm using GraphQL in a Django project and the Altair GraphQL client, and I'm facing an issue with file uploads.
When the request is submitted via Altair, the submitted fields are detected in my ImageUploadMutation
. After initialising the form with the fields (form = ArtistPhotoForm({'photo': file})
), form.data
also prints the right fields.
However, after calling the form.is_valid()
method, I get photo: This field is required
!
Here are the important code segments:
models.py
class ArtistPhoto(models.Model):
# Use width_field and height_field to optimize getting photo's width and height
# This ThumnailerImageField is from easy_thumbnails; but i don't think the issue is here
photo = ThumbnailerImageField(
thumbnail_storage=FILE_STORAGE_CLASS(),
upload_to=ARTISTS_PHOTOS_UPLOAD_DIR,
resize_source=dict(size=(1800, 1800), sharpen=True),
validators=[FileExtensionValidator(['png, jpg, gif'])],
width_field='photo_width',
height_field='photo_height'
)
photo_width = models.PositiveIntegerField()
photo_height = models.PositiveIntegerField()
forms.py
class ArtistPhotoForm(forms.ModelForm):
class Meta:
model = ArtistPhoto
fields = ['photo']
mutation
# Output class contains the fields success and errors
class ImageUploadMutation(graphene.Mutation, Output):
class Arguments:
file = Upload(required=True)
form_for = ImageFormEnum(required=True)
# Apparently this should be an instance method not a class method
@verification_and_login_required
def mutate(self, info, file: InMemoryUploadedFile, form_for, **kwargs):
if form_for == 'artist_photo':
form = ArtistPhotoForm({'photo': file})
if form.is_valid():
print("Form is valid")
print(form.cleaned_data)
return ImageUploadMutation(success=True)
print(form.errors)
return ImageUploadMutation(success=False, errors=form.errors.get_json_data())
I get the error message
{
"data": {
"imageUpload": {
"success": false,
"errors": {
"photo": [
{
"message": "This field is required.",
"code": "required"
}
]
}
}
}
}
I know I could bypass this by manually performing validations directly in the mutation class, but please at least can someone explain to me the source of this error and how to solve it?