Django REST framework: Getting 403 when trying to test create a new post
I'm trying to create a test for creating a new post, but I'm getting Error 403. I've read the questions on this topic, but either they were not about testing or the solution they provided did not work (I'll provide info about what I've tried so far).
Here is my code:
urls.py:
app_name = "blog_api"
urlpatterns = [
path("<str:pk>/", PostDetail.as_view(), name="detail_create"),
path("", PostList.as_view(), name="list_create"),
]
and my permissions.py:
class PostUserWritePermission(permissions.BasePermission):
message = "Editing posts is restricted to the admin and author of the post only."
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_superuser or request.user == obj.author
And here is my views.py:
class PostList(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
queryset = Post.post_objects.all()
serializer_class = PostSerializer
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [PostUserWritePermission]
queryset = Post.post_objects.all()
serializer_class = PostSerializer
And finally, my tests.py:
class PostTests(APITestCase):
def test_view_posts(self):
url = reverse("blog_api:list_create")
response = self.client.get(url, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_create_post(self):
self.test_category = Category.objects.create(name="test category")
self.test_user = User.objects.create_user(
username="test_user",
password="test_password",
)
data = {
"title": "new",
"author": 1,
"excerpt": "new",
"content": "new",
"slug": "new",
}
url = reverse("blog_api:list_create")
response = self.client.post(url, data, format="json")
print(response.data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
So, when I test using py manage.py test
command, the first test is ok, but the second one returns error 403
, and when I tried to see the response message using print(response.data)
this is what's printed:
{'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')}
I should also mention that I have this setting in my settings.py
file:
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticatedOrReadOnly",
],
}
I did some searching about this, this one question was a bit similar to my problem, but I create my user using create_user
method, thus his solution is irrelevant to my question.
What am I missing here?
WHAT I"VE TRIED:
I tried to comment out the permision class PostUserWritePermission
in the PostDetail
view, but got the same error nonetheless.
Also I tried to solve this by adding TokenAuthentication
to my settings, but this didn't work neither.