在Django Rest框架中返回Respose对象时出现NoReverseMatch错误

时间:2019-09-19 09:05:17

标签: python django django-rest-framework

我正在尝试建立Instagram克隆。

单击“跟随”按钮将调用ajax。

我的视图定义文章保存“跟随”并返回Response对象,该对象的数据为true / false值,用于指示是否先前跟踪了用户。

错误消息

//function to show the list item
HRESULT function(datetime, strNumOfGroup, strDisributionRegion, strSpeed){

  m_count = m_hyperTerminal.GetItemCount();

  items = m_hyperTerminal.InsertItem(m_count, datetime);// Five columns in the list control

  m_hyperTerminal.SetItemText(items, 1, strNumOfGroup);
  m_hyperTerminal.SetItemText(items, 2, strCompactness);
  m_hyperTerminal.SetItemText(items, 3, strDistributionRegion);
  m_hyperTerminal.SetItemText(items, 4, strSpeed);
}

views.py

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

urls.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')

ajax

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

你能告诉我为什么会这样吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

在您的例外情况下添加此

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

代替

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

推荐this