【发布时间】: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