In the last article, we created the posts using the admin panel. In this article we will add the posts using the API itself. Keep reading to find out more.
All you have to do is change the instance method from ListAPIView to ListCreateAPIView in views.py as we want to not only want to view the posts but also create them.
Now if you refresh the browser window, then you should see the following:
You can now add posts through the form generated on the page.
Now if you refresh the page, you would be able to see both the posts that you've added.
Now, you might think that's all we had to do to create posts via the API but that's not true. There's more.
When you try to create a Post using the json data and do not put the poster name, it shows that it cannot be null. Ideally the user should not get an option to select the poster. It should be the logged in user.
That's what we're going to change next by making the poster field read-only in the serializer file.
Notice that we also added the poster_id to the fields in class Meta.
Now if we refresh our browser window then we'll notice that there is no poster field in both the HTML form and the json field.
But when we try to fill the data and try to create the post we get the following error saying someone has to be the poster.
So what we can do to solve this error is to override a function just before the API is trying to save the data in the database.
We need to make the following changes in views.py
Now if you refresh and enter the details for the new post, notice it now has a poster and a poster_id field that we just created.
We are able to perform these functions because we are logged in as the user. If we copy the url
http://localhost:8000/api/posts and post it in another browser and try to create a post it would give the following error:
Which basically means that we don't have permission to call the API because we are not authenticated. We need to set that in the views.py file.
Notice that we had to import permissions from rest framework and the instance of the permissions class is 'IsAuthenticatedOrReadonly` which basically means that if you're logged in you can create new post else you can only view the posts, just like reddit.
So, in a browser where you're not logged in you can still view the posts but not create new ones.
But in a browser where you're logged in you can do both.
In the next article, we will write code on how to upvote a particular post. Stay tuned!