Reputation: 113
Good day!
I have a view with detail_route like this:
class PostView(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
@detail_route(methods=['POST'])
def like(self, request, pk=None):
post = self.get_object()
post.like(request.user)
return Response({'result': 'success'})
So, url for like
function is /api/posts/{id}/like
I try testing it with django.test.TestCase
like this:
post = Post.objects.first()
url = reverse('api:post-detail', args=[post.id])
url = urljoin(url, 'like')
response = self.client.post(url, content_type='application/json', follow=True)
I have to use follow=True
because I get code 300 redirect, but redirect return me GET request when I need POST.
I have tried use APIClient
and APIRequestFactory
and got same error or myapp.models.DoesNotExist
Tanks for your attention!
Upvotes: 2
Views: 1013
Reputation: 599450
The fact that you get a 300 at all should be a sign that you're doing something wrong.
Rather than reversing the main URL and then joining the detail route extension manually, you should reverse directly to the full URL you want. As the docs for detail_route
show, that decorator gives you a named route in the form <model>-<detail-method>
. So:
url = reverse('api:post-like', args=[post.id])
response = self.client.post(url, content_type='application/json')
Upvotes: 4