Uploading images/files using Django(graphene-django) and graphene-file-upload
Hey there, in this article, I will discuss how I implemented uploading images using graphql and Django. Most part of this article can also be used when uploading files.
Tools/libraries used:
- graphene-file-upload: It seemed simpler to use graphene-file-upload and also it supports multi-part file uploads.
- We use graphene-django for the project which is a Django integration for graphene.
The implementation:
In our models.py file, we have our Company model as shown below:
In our Company model, we have the logo field that is a Django ImageField. This is the field to which we are to upload the image.
We then install graphene-file-upload that will carry out the image uploading swiftly:
pip install graphene-file-upload
After installation is done, in the urls.py file, we then replace our previous Graphql view with the FileUploadGraphQLView from graphene_file_upload
from graphene_file_upload.django import FileUploadGraphQLView
urlpatterns = [
url(r'^graphql', FileUploadGraphQLView.as_view(graphiql=True)),
]
We then create a form, for validation purposes, although I didn't include the validation bit, and the CreateCompanyMutation class view as follows:
In the mutations.py file, we use the graphene-file-upload scalar type, Upload, as our logo input type and add required=False argument as it wouldn't be a required input when creating a company.
In case the image is uploaded, it will be added to the file_data dictionary(line 22) and bound(line 26) to the CreateCompanyMutationForm, from where it would then be uploaded to the Company model field, logo.
Don’t forget to add CreateCompanyMutation to the main mutation class i.e.
create_company = CreateCompanyMutation.Field()
We can test a request sent to CreateCompanyMutation view by using tools like insomnia or postman, as of now, I don't think there is a way of making this request with a file/image using graphiql.
Below I show the structure of the request in insomnia, which can also be done in postman.
In insomnia, we need to select the content type of the request to be Multipart Form and create 3 parameters for this. These are operations, map, and 0.
0 is the image to be uploaded, operations(Text(Multi-line)) is the query mutation, and map(Text(Multi-line)) contains a mapping to the logo variable in operations as shown below.
In the Header, we need to add the Content-Type as multipart/form-data.
And we are done. We are ready to make the request. Hopefully, this article was helpful in any way to you.
Thanks for reading.