![](/img/trans.png)
[英]Django REST Framework - NoReverseMatch when using reverse()
[英]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.