【问题标题】:NoReverseMatch error when returning Respose object in django rest framework在 django rest 框架中返回 Respose 对象时出现 NoReverseMatch 错误
【发布时间】:2020-01-20 06:41:19
【问题描述】:

我正在尝试构建 Instagram 克隆。

点击关注按钮调用ajax。

我的视图 def post 保存“follows”并返回 Response 对象,其数据为 true/false 值,用于判断用户之前是否被关注。

错误信息

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

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

urls.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))
         }
});

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

提前谢谢你。

【问题讨论】:

  • 我认为 target_user.username 在 ajax URL 中变得空白
  • 也许可以试试这个:url: '{% url 'profile' target_user.username %}', 还有insta_profile 它在你的网址中指向哪里?
  • 请显示您渲染包含 ajax 的模板的视图。
  • with arguments '('',)' 表示target_user 未设置或target_user.username 未设置,或者错误来自您未显示的另一个{% url %} 标签。
  • 这是什么时候发生的?当您实际单击“关注”按钮时?或者当你渲染这个按钮应该显示的模板时?

标签: python django django-rest-framework


【解决方案1】:

在你的异常中添加这个

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

而不是

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

参考this

【讨论】:

  • 感谢您的回答,但它不会引发 DoesNotExist
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
相关资源
最近更新 更多