How do you upload images using Django REST Framework? Could you imagine if it was similar to using regular everyday Django?
Follow this mini tutorial and you’ll find out! :)
If you want to follow along, I have a git repository you can find here.
Want to get started learning Django REST Framework? Sign up for a FREE 7 Day Email Course today. Click here for more information
The first thing you should do is set your
MEDIA_ROOT variables. For the sake of this example, I’m just going to use
/media/ as both the URL and the ROOT directories.
Now, in our app, I just create a simple
FileField. But, if you just want to allow uploading Images, you would using
Let’s look at my
Serializer we are going to use is pretty simple:
And finally, we will need a
View that can parse a multipart and a form so we can fully support any kind of HTML form data.
We use the class-based
View attribute for
parser_classes to allow the
View to parse both MultiPart and Form data.
url we use looks like this:
We are finished! Let’s give it a go!
I use Postman to test REST APIs. So, let’s check it out. First download Postman here.
Next, let’s run our application.
- Now, let’s open up Postman.
- In the address bar type in:
- Then, in the request method dropdown, select
Send and you should see the following
This means that we didn’t select a file to upload. Let’s do that now:
Body tab and under
Key there is a hidden dropdown called
Text. Switch it to
Next, select the
file that we want to upload. Then, type in
description as a second key-value pair and type in a description.
You should get the following
Congratulations! You just learned how to upload a File using Django REST Framework. And you learned how to test using Files using Postman.
You may use my code next time you need to allow files in Django REST Framework.