簡體   English   中英

在 django rest 框架中返回 Respose object 時出現 NoReverseMatch 錯誤

[英]NoReverseMatch error when returning Respose object in django rest framework

我正在嘗試構建 Instagram 克隆。

單擊關注按鈕調用 ajax。

我的視圖 def post 保存“關注”並返回響應 object,其數據為真/假值,表示用戶之前是否被關注。

錯誤信息

‘django.urls.exceptions.NoReverseMatch: Reverse for 'profile' 
with arguments '('',)' not found. 2 pattern(s) tried’

視圖.py

class ProfileListView(mixins.UpdateModelMixin, generics.GenericAPIView):
    """User post list"""
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'insta/profile_list.html'
    serializer_class = InstaSerializer
    permission_classes = [permissions.AllowAny]

    def get(self, request, *args, **kwargs):
        target = kwargs.get('username')
        try:
            target_user = USER.objects.get(username=target)
            response = Insta.objects.filter(owner__username=target)
            return Response({'posts': response, 'target_user': target_user})
        except USER.DoesNotExist:
            return HttpResponseRedirect(reverse('insta:dashboard'), status=HTTP_404_NOT_FOUND)

    def post(self, request, *args, **kwargs):
        followed_user = get_object_or_404(USER, username=kwargs.get('username'))

        if request.user.is_authenticated:
            follower_user = request.user
            if followed_user == follower_user:
                raise PermissionError('Unable to follow yourself')
            else:
                if follower_user in followed_user.followers.all():
                    followed_user.followers.remove(follower_user)
                    return Response({
                        'follow_exist': False
                    })
                else:
                    follower_user.follows.add(followed_user)
                    return Response({
                        'follow_exist': True
                    })
        else:
            return redirect('insta/login')

網址.py

path('<username>/', insta_profile, name='profile'),

ajax

$.ajax({
        type: 'POST',
        url: '{% url 'insta:profile' username=target_user.username %}',
        data: {'csrfmiddlewaretoken': '{{ csrf_token }}'},
        success: function (response) {
            if (response.follow_exist) {
                $this.attr('class', 'btn btn-outline-secondary');
                $this.text('cancel follow')
            } else {
                $this.attr('class', 'btn btn-primary');
                $this.text('follow')
            }
         },
         error: function (response) {
            console.log(JSON.stringify(response))
         }
});

你能告訴我為什么會這樣嗎?

先感謝您。

在你的例外中添加這個

 return HttpResponseRedirect(reverse('insta:dashboard', args=(username,), status=HTTP_404_NOT_FOUND)

代替

    return HttpResponseRedirect(reverse('insta:dashboard'), status=HTTP_404_NOT_FOUND)

參考這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM